场景分析;
2.实例代码;
1.安装相关支持包 pip3 install pycrypto pip3.6 install paramiko 2.远程执行命令示例代码; #!/usr/bin/env python36 from multiprocessing import Process import paramiko import sys Username = 'root' Password = 'P@ssw0rd' Port = 22 TimeOut = 60 def runCmd(ip,cmd): s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: s.connect(hostname=ip, port=Port, username=Username, password=Password,timeout=TimeOut) stdin, stdout, stderr = s.exec_command(cmd) result = stdout.read() print(ip,result) except: print("is not exists") + ip def ipProcess(): try: cmd = sys.argv[1] for i in range(4,16): ip = '172.21.38.%s' % i p = Process(target=runCmd,args=(ip,cmd)) p.start() except IndexError: print("please input a command") if __name__ == '__main__': ipProcess()
3.执行结果;
python3.6 bbc_init.py uptime
4.封装远程命令执行和文件上传;
#!/usr/bin/env python # -*- coding:utf-8 -*- import paramiko class SSHConnection(object): def __init__(self, host='192.168.12.68', port=22, username='locojoy',pwd='123321QQ!'): self.host = host self.port = port self.username = username self.pwd = pwd self.__k = None def run(self): self.connect() # 连接远程服务器 self.upload('db.py','/tmp/1.py') # 将本地的db.py文件上传到远端服务器的/tmp/目录下并改名为1.py self.cmd('df') # 执行df 命令 self.close() # 关闭连接 def connect(self): transport = paramiko.Transport((self.host, self.port)) transport.connect(username=self.username, password=self.pwd) self.__transport = transport def close(self): self.__transport.close() def upload(self,local_path,target_path): sftp = paramiko.SFTPClient.from_transport(self.__transport) sftp.put(local_path,target_path) def cmd(self, command): ssh = paramiko.SSHClient() ssh._transport = self.__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command(command) # 获取命令结果 result = stdout.read() print(result) return result obj = SSHConnection() obj.run()