用python脚本执行ssh远程登录多台机器

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的一个脚本,拿过来可以配合使用得到彩色输出
Python代码   收藏代码
  1.   1. #!/usr/bin/python   
  2.   2. import sys    
  3.   3. import os    
  4.   4. import getopt    
  5.   5. import pexpect    
  6.   6. try:    
  7.   7.    from ansi_color import * #就是我前面帖子里关于ansi_color的几个定义    
  8.   8. except ImportError:    
  9.   9.    def color_str(s, *args):    
  10.  10.        return s    
  11.  11.    fg_green = None    
  12.  12.    fg_red = None    
  13.  13.    fg_blue = None    
  14.  14. password="123456" #替换成你自己的密码。    
  15.  15. def do(cmds, dst, username, outfile):    
  16.  16.    global verbose, is_quiet, good_hosts    
  17.  17.    print "executing \"%s\""%(repr(cmds))    
  18.  18.    try:    
  19.  19.        prompt = "^.*\(.*\):|\$"    
  20.  20.        hostname = dst    
  21.  21.        sshcmd = '<b style="color: black; background-color: rgb(153, 255, 153);">ssh</b> %s'%(hostname)    
  22.  22.        if username != None:    
  23.  23.            sshcmd = sshcmd + " -l %s"%username    
  24.  24.        s = pexpect.spawn(command=sshcmd, timeout=20)    
  25.  25.        s.logfile_read = outfile    
  26.  26.        s.setecho(True)    
  27.  27.        i = -1    
  28.  28.        while (i<>0):    
  29.  29.            i = s.expect([prompt,"Are you sure you want to continue connecting (yes/no)?","Password:"])    
  30.  30.            if i == 1:    
  31.  31.                s.sendline("yes")    
  32.  32.            elif i == 2:    
  33.  33.                s.sendline(password)    
  34.  34.        for cmd in cmds:         
  35.  35.            s.sendline(cmd)    
  36.  36.            s.expect(prompt)    
  37.  37.        s.sendline("exit")    
  38.  38.        s.close()    
  39.  39.        if verbose:    
  40.  40.            print    
  41.  41.        print "["+color_str("OK!", fg_green)+"]"    
  42.  42.        if recording:    
  43.  43.            print>>f_good, hostname    
  44.  44.            f_good.flush()    
  45.  45.        good_hosts.append(hostname)    
  46.  46.    except pexpect.ExceptionPexpect:    
  47.  47.        if verbose:    
  48.  48.            print    
  49.  49.        print "["+color_str("Fail!", fg_red)+"]"    
  50.  50.        if recording:    
  51.  51.            print>>f_bad, hostname    
  52.  52.            f_bad.flush()    
  53.  53.        bad_hosts.append(hostname)    
  54.  54. def print_usage():    
  55.  55.    print "Usage:\t ./make_do.py -f cmdfile -l username -c cmd -n nodesfile -v -r"    
  56.  56.    print "execut cmd on remote hosts (all hosts in ./hosts.txt by default)"    
  57.  57.    print "\t-v verbose"    
  58.  58.    print "\t-r recording hosts on which mission succeeded and failed"    
  59.  59.    print "\t-l username"    
  60.  60.    print "\t-c cmd to be executed remotely"    
  61.  61.    print "\t-n file containing the nodes"    
  62.  62.    print "\t-f file conaining the cmd"    
  63.  63.    print "\t-h show the usage"    
  64.  64.    sys.exit(-1)    
  65.  65. if __name__ == "__main__":    
  66.  66.    try:    
  67.  67.        opts, args=getopt.getopt(sys.argv[1:], "l:f:n:c:vhr",["login_name""cmdfile","nodesfile","command","help","verbose""recording"])    
  68.  68.    except getopt.GetoptError, err:    
  69.  69.        print str(err)    
  70.  70.        print_usage()    
  71.  71.    if opts == [] and args == []:    
  72.  72.        print_usage()    
  73.  73.    hosts = None    
  74.  74.    cmds = None    
  75.  75.    outfile = open("/dev/null""w")    
  76.  76.    verbose = False    
  77.  77.    username = None    
  78.  78.    recording = False    
  79.  79.    for o, ra in opts:    
  80.  80.        a = ra.strip(" \t\n")    
  81.  81.        if o in ("-h""--help"):    
  82.  82.            print_usage()    
  83.  83.        elif o in ("-n""--nodesfile"):    
  84.  84.            h = open(a, 'r')    
  85.  85.            hosts = [l.strip(" \t\n"for l in h]    
  86.  86.        elif o in ("-c""--command"):    
  87.  87.            cmds = [a]    
  88.  88.        elif o in ("-f""--cmdfile"):    
  89.  89.            cmdfile =  open(a, "r")    
  90.  90.            cmds = [cmd.strip(' \n'for cmd in cmdfile]    
  91.  91.        elif o in ("-v",  "--verbose"):    
  92.  92.            outfile = sys.stdout    
  93.  93.            verbose = True    
  94.  94.        elif o in ("-r""--recording"):    
  95.  95.            recording = True    
  96.  96.        elif o in ("-l""--login_name"):    
  97.  97.            username = a    
  98.  98.    if hosts is None:    
  99.  99.        print "using default ./hosts.txt"    
  100. 100.        h = open(os.path.join(os.path.expanduser("."), "hosts.txt"),'r')    
  101. 101.        hosts = [dst.strip(' \n'for dst in h]    
  102. 102.    if cmds is None:    
  103. 103.        print "-c or -f must specified"    
  104. 104.        print_usage()    
  105. 105.    if recording:    
  106. 106.        f_good = open("good_hosts.txt","w")    
  107. 107.        f_bad = open("bad_hosts.txt","w")    
  108. 108.    good_hosts =[]    
  109. 109.    bad_hosts =[]    
  110. 110.    for i in range(len(hosts)):    
  111. 111.        dst = hosts[i]    
  112. 112.        print "%d/%d: ["%(i+1, len(hosts))+ color_str(dst, fg_blue)+"]"    
  113. 113.        do(cmds, dst, username, outfile)    
  114. 114.    print "%d hosts suceed!"%len(good_hosts)    
  115. 115.    outfile.close()    
  116. 116.    h.close()    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现远程ssh登录可以使用Python的paramiko库,抓取网卡的带宽和速度可以使用psutil库。 以下是示例代码: ```python import paramiko import psutil def ssh_connect(host, username, password): '''连接远程服务器''' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=username, password=password) return ssh def get_network_speed(ssh): '''获取网卡带宽和速度''' stdin, stdout, stderr = ssh.exec_command('cat /proc/net/dev') result = stdout.read().decode() lines = result.split('\n') for line in lines: if 'eth0' in line: data = line.split(':') stats = data[1].split() rx_bytes = int(stats[0]) tx_bytes = int(stats[8]) break rx_speed = psutil.net_io_counters().bytes_recv - rx_bytes tx_speed = psutil.net_io_counters().bytes_sent - tx_bytes return rx_speed, tx_speed if __name__ == '__main__': host = 'your_host' username = 'your_username' password = 'your_password' ssh = ssh_connect(host, username, password) rx_speed, tx_speed = get_network_speed(ssh) print('RX speed: {} bytes/s'.format(rx_speed)) print('TX speed: {} bytes/s'.format(tx_speed)) ssh.close() ``` 其中,`ssh_connect()`函数用于远程连接服务器,`get_network_speed()`函数用于获取网卡带宽和速度。在`get_network_speed()`函数中,首先使用`ssh.exec_command()`方法执行`cat /proc/net/dev`命令获取网卡信息,然后解析返回的结果,获取网卡的接收字节数和发送字节数。接着,使用psutil库获取当前系统的接收字节数和发送字节数,计算出网卡的带宽和速度。 注意,本示例代码仅供参考,具体实现应根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值