python paramiko

利用上班休息时间写了一个小程序,利用 paramiko 实现单次的连接服务器--->执行命令(待完善的功能,应该是一次连接批量执行 command,并且不支持实时命令返回结果, 后续进行完善,在此做此记录)

 1 #!/usr/bin/env python
 2 # _*_coding:utf-8_*_
 3 #  author:  'Edward.Liu'
 4 # dateTime:  '15/12/4'
 5 #   motto:  'Good memory as bad written'
 6 
 7 import paramiko
 8 import getpass
 9 
10 
11 def ssh_clients(hostname=None, port=22, username=None, password=None, command=None, nbytes=4096):
12     client = paramiko.Transport((hostname, port))
13     client.connect(username=username, password=password)
14 
15     stdout_data = []
16     stderr_data = []
17     session = client.open_channel(kind='session')
18     session.exec_command(command)
19     while True:
20         if session.recv_ready():
21             stdout_data.append(session.recv(nbytes))
22         if session.recv_stderr_ready():
23             stderr_data.append(session.recv_stderr(nbytes))
24         if session.exit_status_ready():
25             break
26 
27     print '\033[32mExit status is: \033[0m', session.recv_exit_status()
28     print "\033[31m*********************\033[0m"
29     print ''.join(stdout_data)
30     print ''.join(stderr_data)
31     session.close()
32     client.close()
33 
34 
35 if __name__ == '__main__':
36     host_list = ['x.x.x.x', 'x.x.x.x', 'x.x.x.x']#服务器地址列表
37     print "\033[31m     **********IPaddress List**********      \033[0m"
38     for index, value in enumerate(host_list):
39         print index, value
40     chose_ip = raw_input("\033[32mPlease Connection Host IP Or Host Name:\033[0m").strip()
41     if chose_ip.isdigit():
42         chose_ip = int(chose_ip)
43         hostname = host_list[chose_ip]
44     username = raw_input("\033[32mPlease Input Will Connection Host User:\033[0m").strip()
45     password = getpass.getpass("\033[32mEnter You Password:\033[0m").strip()
46     if len(username) == 0 and len(password) == 0:
47         username = 'user' #远程服务器用户,此处为默认用户适用一组服务器
48         password = 'password' #远程服务器密码
49     command = raw_input("\033[32mPlease Input Will Running Command:\033[0m").strip()
50     ssh_clients(hostname=hostname, username=username, password=password, command=command)
51     print "\033[32m--------------------SSH_Connection Info--------------------\033[0m"
52     print "\033[32m|    **********SSH_Connection-->Host:%s\033[0m" % hostname
53     print "\033[32m|    **********SSH_Connection-->User:%s\033[0m" % username
54     print "\033[32m|    **********SSH_Connection-->Passwd:%s\033[0m" % password
55     print "\033[32m|    **********SSH_Connection-->RunCMD:%s\033[0m" % command
56     print "\033[32m--------------------SSH_Connection END--------------------\033[0m"
View Code

 

你可能感兴趣的:(python paramiko)