# coding=utf8 import paramiko """ /* python -m pip install paramiko python version 3.7 author Chen,Date:2019.2.10 */ """ class SSH(object): def __init__(self,host,port,user,pwd): self.host=host self.port=port self.user=user self.pwd=pwd """其实这样写不是最好办法,解决多行根本是paramiko执行机制,每次执行完ssh.exec_command()函数会自动回到session初始化root路径,多行建议以;分号隔开""" def ssh_connect(self,**shell): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.host,self.port,self.user,self.pwd) self.ssh=ssh for key in shell: stdin, stdout, stderr = self.ssh.exec_command(shell[key]) res,err = stdout.read(),stderr.read() result = res if res else err print(result.decode("utf-8")) self.ssh.close() """ /* 注意点:remote_path 和 local_path , 路径必须为带文件名全路径只到目录路径会报: [Errno 13] Permission denied,若路径怕出错可以在最前面加r */ """ def sftp_get_from_linux(self,remote_path,local_path): try: transport = paramiko.Transport((self.host ,self.port)) transport.connect(username=self.user,password=self.pwd) sftp=paramiko.SFTPClient.from_transport(transport) sftp.get(remotepath=remote_path,localpath=local_path) transport.close() except Exception as e: print(e) else: print("下载ok") def sftp_put_to_linux(self,local_path,remote_path): try: transport = paramiko.Transport((self.host ,self.port)) transport.connect(username=self.user,password=self.pwd) sftp=paramiko.SFTPClient.from_transport(transport) sftp.put(localpath=local_path,remotepath=remote_path) transport.close() except Exception as e: print(e) else: print("上传ok") if __name__ == "__main__": ssh_exe=SSH("192.168.229.128",22,"root","123456") ssh_exe.ssh_connect(shell1="df",shell2="cd /etc;ps -ef|grep java;pwd;") # ssh_exe.sftp_windows_from_linux(remote_path="/root/install.log",local_path="C:/Users/Administrator/Desktop/py/test_linux.log") # ssh_exe.sftp_put_to_linux("C:/Users/Administrator/Desktop/py/test_linux.log","/root/test_python.log")
C:\Python37\python.exe C:/Users/Administrator/PycharmProjects/pytestframe/pc/sshconnect.py
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda2 8985528 3386332 5142748 40% /
tmpfs 515264 376 514888 1% /dev/shm
/dev/sda1 297485 32808 249317 12% /boot
root 4011 4002 0 01:43 ? 00:00:00 bash -c cd /etc;ps -ef|grep java;pwd;
root 4017 4011 0 01:43 ? 00:00:00 grep java
/etc
Process finished with exit code 0