Scene analysis;
2. The example code;
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. The results of the implementation;
python3.6 bbc_init.py uptime
4. Package remote command execution and file upload;
! # / usr / bin / Python the env # - * - Coding: UTF-. 8 - * - Import paramiko class SSHConnection (Object): DEF the __init __ (Self, Host = '192.168.12.68', Port = 22 is, username = 'locojoy ', pwd =' 123321QQ '):! self.host = Host self.port = Port self.username = username self.pwd pwd = Self .__ K = None DEF RUN (Self): self.connect () connected to a remote server # under self.upload ( 'db.py', '/ tmp / 1.py') # db.py the local to the remote server's file upload / tmp / directories and renamed 1.py self.cmd ( 'DF ') # df command execution self.close () # close the connection DEF connect (Self): Transport paramiko.Transport = ((self.host, self.port)) transport.connect (= self.username 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()