现在的位置: 首页 > 编程语言 > 正文

python ssh2远程登录节点并执行命令

2019年09月29日 编程语言 ⁄ 共 1382字 ⁄ 字号 评论关闭

root@node7:/opt# vim pyssh2.py

#!/usr/bin/python
"""
SSH connect to remote machines and then execute what
you need command
"""
import paramiko # import paramiko && help(paramiko) || pydoc paramiko
import threading

#debug = True

#class SSHClass(objiect):
#    "class"

def pyssh2(ip, username, passwd, cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, passwd, timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
#            stdin.write("Y")   #simple interaction, default input 'Y'
            out = stdout.readlines()
            #output to screen    
            for o in out:
                print o,
            print '%s\tOK\n' % (ip),
            ssh.close()
    except Exception, e:
        print 'ERR: can not find remote host %s' % (ip), e

if __name__=='__main__':
    cmd = ['hostname']#need to execute cmd
    username = "root"#username
    passwd = "123123"    #password
    threads = []   #multi thread
    print "Prompt:begin to connect remote machines......"
    for i in range(150,156):
          ip = '10.100.1.'+str(i)
          a=threading.Thread(target=pyssh2,args=(ip,username,passwd,cmd)) #used default arguments
#          __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None)
#          a=threading.Thread()
#          a.__init__(group=None, target=pyssh, name=None, args=(ip,username,passwd,cmd),
#                 kwargs=None, verbose=None)
          a.start()

抱歉!评论已关闭.