设为首页 收藏本站
查看: 1717|回复: 0

[经验分享] [Python]一个用ssh来远程登录多台机器并执行命令的脚本

[复制链接]

尚未签到

发表于 2017-5-7 06:15:33 | 显示全部楼层 |阅读模式

Kids Return: [Python
]一个用ssh
来远程登录
多台机器并执行命令的脚本


[Python
]一个用ssh
来远程登录
多台机器并执行命令的脚本 ....
阅读器无法显示某些pdf文档的中文问题 · Ubuntu以及MacOS下使用街机模拟
器Mame · [Python
]Python
3.0来了 ...

apc999.blogspot.com/2009/01/python
_19.html -
网页快照
- 类似结果



来源:apc999.blogspot.com/2009/01/python
_19.html(以上为GOOGLE搜索结果,因blogspot被墙了,故转载止此处,供己收藏,亦与众分享)






功能类似于multissh。事实上我也抄了这个名字//grin。

要求安装了pexpect
这个包先。

用法见usage:

Usage:     ./multissh.py -f cmdfile -l username -c cmd -n nodesfile -v -r

execut cmd on remote hosts (all hosts in ./hosts.txt by default)

-v verbose

-r recording hosts on which mission succeeded and failed

-l username

-c cmd to be executed remotely

-n file containing the nodes

-f file conaining the cmd

-h show the usage

就是指定一个文件比如nodes.txt以及命令以后,它可以自动登录
到nodes.txt包含的节点里执行命令。可以在源文件里替换进你自己的密码,也可以使用公钥密钥登录
不需输入密码。指定了v选项的话得到在远端每台主机上的详细输出。指定了r选项的话记录下那些节点成功那些节点失败。

我前面的帖子里有关于ansi_color的一个脚本,拿过来可以配合使用得到彩色输出

   1. #!/usr/bin/python
2. import sys  
3. import os  
4. import getopt  
5. import pexpect  
6. try:  
7.    from ansi_color import * #就是我前面帖子里关于ansi_color的几个定义  
8. except ImportError:  
9.    def color_str(s, *args):  
10.        return s  
11.    fg_green = None  
12.    fg_red = None  
13.    fg_blue = None  
14. password="123456" #替换成你自己的密码。  
15. def do(cmds, dst, username, outfile):  
16.    global verbose, is_quiet, good_hosts  
17.    print "executing \"%s\""%(repr(cmds))  
18.    try:  
19.        prompt = "^.*\(.*\):|\$"  
20.        hostname = dst  
21.        sshcmd = '<b style="color: black; background-color: rgb(153, 255, 153);">ssh</b> %s'%(hostname)  
22.        if username != None:  
23.            sshcmd = sshcmd + " -l %s"%username  
24.        s = pexpect.spawn(command=sshcmd, timeout=20)  
25.        s.logfile_read = outfile  
26.        s.setecho(True)  
27.        i = -1  
28.        while (i<>0):  
29.            i = s.expect([prompt,"Are you sure you want to continue connecting (yes/no)?","Password:"])  
30.            if i == 1:  
31.                s.sendline("yes")  
32.            elif i == 2:  
33.                s.sendline(password)  
34.        for cmd in cmds:      
35.            s.sendline(cmd)  
36.            s.expect(prompt)  
37.        s.sendline("exit")  
38.        s.close()  
39.        if verbose:  
40.            print  
41.        print "["+color_str("OK!", fg_green)+"]"  
42.        if recording:  
43.            print>>f_good, hostname  
44.            f_good.flush()  
45.        good_hosts.append(hostname)  
46.    except pexpect.ExceptionPexpect:  
47.        if verbose:  
48.            print  
49.        print "["+color_str("Fail!", fg_red)+"]"  
50.        if recording:  
51.            print>>f_bad, hostname  
52.            f_bad.flush()  
53.        bad_hosts.append(hostname)  
54. def print_usage():  
55.    print "Usage:\t ./make_do.py -f cmdfile -l username -c cmd -n nodesfile -v -r"  
56.    print "execut cmd on remote hosts (all hosts in ./hosts.txt by default)"  
57.    print "\t-v verbose"  
58.    print "\t-r recording hosts on which mission succeeded and failed"  
59.    print "\t-l username"  
60.    print "\t-c cmd to be executed remotely"  
61.    print "\t-n file containing the nodes"  
62.    print "\t-f file conaining the cmd"  
63.    print "\t-h show the usage"  
64.    sys.exit(-1)  
65. if __name__ == "__main__":  
66.    try:  
67.        opts, args=getopt.getopt(sys.argv[1:], "l:f:n:c:vhr",["login_name", "cmdfile","nodesfile","command","help","verbose", "recording"])  
68.    except getopt.GetoptError, err:  
69.        print str(err)  
70.        print_usage()  
71.    if opts == [] and args == []:  
72.        print_usage()  
73.    hosts = None  
74.    cmds = None  
75.    outfile = open("/dev/null", "w")  
76.    verbose = False  
77.    username = None  
78.    recording = False  
79.    for o, ra in opts:  
80.        a = ra.strip(" \t\n")  
81.        if o in ("-h", "--help"):  
82.            print_usage()  
83.        elif o in ("-n", "--nodesfile"):  
84.            h = open(a, 'r')  
85.            hosts = [l.strip(" \t\n") for l in h]  
86.        elif o in ("-c", "--command"):  
87.            cmds = [a]  
88.        elif o in ("-f", "--cmdfile"):  
89.            cmdfile =  open(a, "r")  
90.            cmds = [cmd.strip(' \n') for cmd in cmdfile]  
91.        elif o in ("-v",  "--verbose"):  
92.            outfile = sys.stdout  
93.            verbose = True  
94.        elif o in ("-r", "--recording"):  
95.            recording = True  
96.        elif o in ("-l", "--login_name"):  
97.            username = a  
98.    if hosts is None:  
99.        print "using default ./hosts.txt"  
100.        h = open(os.path.join(os.path.expanduser("."), "hosts.txt"),'r')  
101.        hosts = [dst.strip(' \n') for dst in h]  
102.    if cmds is None:  
103.        print "-c or -f must specified"  
104.        print_usage()  
105.    if recording:  
106.        f_good = open("good_hosts.txt","w")  
107.        f_bad = open("bad_hosts.txt","w")  
108.    good_hosts =[]  
109.    bad_hosts =[]  
110.    for i in range(len(hosts)):  
111.        dst = hosts  
112.        print "%d/%d: ["%(i+1, len(hosts))+ color_str(dst, fg_blue)+"]"  
113.        do(cmds, dst, username, outfile)  
114.    print "%d hosts suceed!"%len(good_hosts)  
115.    outfile.close()  
116.    h.close()  


 另附一个邮件列表组的讨论内容:


python-cn邮件列表 写道



python
能不能模拟键盘输入字符,类似于TCL的post,比如在我用SSH
连接到LINUX,然后用PYTHON
来输入ls命令。急用




pyexpect


2008/11/25 zhezh80 <zhezh80@...>:

> python能不能模拟键盘输入字符,类似于TCL的post,比如在我用SSH连接到LINUX,然后用PYTHON来输入ls命令。急用

>


你这个并非模拟键盘输入,

而仅仅是远程通过 ssh 执行命令,


请阅以前讨论过的 python-paramiko

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-373942-1-1.html 上篇帖子: 定时任务管理之python篇celery使用 下篇帖子: Python基础教程笔记——条件,循环和其他语句(转)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表