1 import paramiko
2 import sys
3 import getpass
4 import threading
5 import os
6
7 def rcmd(host=None, port=22, user='root', passwd=None, command=None):
8 ssh = paramiko.SSHClient()
9 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
10 ssh.connect(hostname=host, username=user, password=passwd, port=port)
11 _, stdout, stderr = ssh.exec_command(command)
12 out = stdout.read()
13 err = stderr.read()
14 if out:
15 print('[%s] OUT:\n%s' % (host, out.decode()))
16 if err:
17 print('[%s] ERROR:\n%s' % (host, err.decode()))
18 ssh.close()
19
20 if __name__ == '__main__':
21 # rcmd('192.168.4.6', passwd='123456', command='id root; id wangwu')
22 if len(sys.argv) != 3:
23 print('Usage: %s ipfile "command"' % sys.argv[0])
24 exit(1)
25 if not os.path.isfile(sys.argv[1]):
26 print('No such file:', sys.argv[1])
27 exit(2)
28
29 ipfile = sys.argv[1]
30 command = sys.argv[2]
31 password = getpass.getpass()
32 with open(ipfile) as fobj:
33 for line in fobj:
34 ip = line.strip() # 删除行尾的\n
35 # rcmd(ip, passwd=password, command=command)
36 t = threading.Thread(target=rcmd, args=(ip,), kwargs={'passwd': password, 'command': command})
37 t.start()