I. Introduction
Paramiko Remote SSH connection module is implemented in Python, SSH for remote execution of commands, file transfer functions based.
Installation Module
The default Python does not own, you need to manually install:
pip3 install paramiko
Second, upload files
# ! / Usr / bin / env python3 # Coding: UTF-8 Import paramiko DEF sftp_upload_file (Host, the User, password, server_path, local_path, timeout = 10 ): "" " upload files, note: does not support folders : param host : host name : param user: username : param password: password : param server_path: remote path, such as: /home/sdn/tmp.txt : param local_path: local path, such as: D: /text.txt : param timeout: timeout (default), must be of type int : return: BOOL "" " the try : T = paramiko.Transport ((Host, 22 is )) t.banner_timeout = timeout t.connect (username=user, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(local_path, server_path) t.close() return True except Exception as e: print(e) return False
Upload test, complete code is as follows:
# ! / Usr / bin / env python3 # Coding: UTF-8 Import paramiko DEF sftp_upload_file (Host, the User, password, server_path, local_path, timeout = 10 ): "" " upload files, note: does not support folders : param host : host name : param user: username : param password: password : param server_path: remote path, such as: /home/sdn/tmp.txt : param local_path: local path, such as: D: /text.txt : param timeout: timeout (default), must be of type int : return: BOOL "" " the try : T = paramiko.Transport ((Host, 22 is )) t.banner_timeout = timeout t.connect (username=user, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(local_path, server_path) t.close() return True except Exception as e: print(e) return False if __name__ == '__main__': host = '192.168.10.1' user = 'xiao' password = 'xiao@1234' server_path = '/tmp/tmp.txt ' local_path = ' D: /text.txt ' RES = sftp_upload_file (Host, User, password, the server_path, local_path) IF Not RES: Print ( " Upload File:% s Failed " % local_path) the else : Print ( " upload files:% s successful " % local_path)
Perform output:
Upload file: D: /text.txt success
Third, download the file
DEF sftp_down_file (Host, the User, password, server_path, local_path, timeout = 10 ): "" " Download file Note: does not support folders : param host: Host Name : param user: Username : param password: password : param server_path : remote location, such as: /home/sdn/tmp.txt : param local_path: local path, such as: D: /text.txt : param timeout: timeout (default), must be of type int : return: BOOL "" " the try : T = paramiko.Transport ((Host, 22 is )) t.banner_timeout = timeout t.connect (username = User, password = password) SFTP = paramiko.SFTPClient.from_transport (T) sftp.get (the server_path, local_path) t.close() return True except Exception as e: print(e) return False
Test, download files function, complete code is as follows:
# ! / Usr / bin / env python3 # Coding: UTF-8 Import paramiko DEF sftp_down_file (Host, the User, password, server_path, local_path, timeout = 10 ): "" " Download file Note: does not support folders : param host : host name : param user: username : param password: password : param server_path: remote path, such as: /home/sdn/tmp.txt : param local_path: local path, such as: D: /text.txt : param timeout: timeout (default), must be of type int : return: BOOL "" " the try : T = paramiko.Transport ((Host, 22 is )) t.banner_timeout = timeout t.connect (username=user,password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(server_path, local_path) t.close() return True except Exception as e: print(e) return False if __name__ == '__main__': host = '192.168.10.1' user = 'xiao' password = 'xiao@1234' server_path = '/tmp/tmp.txt ' local_path = ' D: /text.txt ' RES = sftp_down_file (Host, User, password, the server_path, local_path) IF Not RES: Print ( " Download File:% s Failed " % the server_path) the else : Print ( " Download file:% s successful " % server_path)
Perform output:
Download file: /tmp/tmp.txt success
Fourth, remote command execution
DEF ssh_exec_command (Host, the User, password, cmd, timeout = 10 ): "" " Use ssh to connect to remote server to execute the command : param host: Host Name : param user: Username : param password: password : param cmd: command execution : param seconds: timeout (default), must be of type int : return: dict "" " result = { ' Status ' :. 1, ' Data ' : None} # return a result the try : SSH = paramiko.SSHClient () # Create SSHClient a new instance of ssh.banner_timeout = timeout #Set host key, if the relevant information is not stored in the "known_hosts" in, SSHClient default behavior is to deny access, you will be prompted yes / NO ssh.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) ssh.connect (Host, 22, the User, password, timeout = timeout) # connect to a remote server, one second timeout stdin, stdout, stderr = ssh.exec_command (cmd, get_pty = True, timeout = timeout) # Run OUT = stdout.readlines () # execution result, returns the readlines listing # execution state, 0 for success, 1 indicates failure Channel = stdout.channel status = channel.recv_exit_status () ssh.close () # close connection ssh # returns the modified result result [ 'Status ' ] = Status Result [ ' Data ' ] = OUT return Result the except Exception AS E: Print (E) Print ( " Error, failed login server IP:! {} " .format (Host)) return False
Test, remote command execution function, complete code is as follows:
# ! / Usr / bin / env python3 # Coding: UTF-8 Import paramiko DEF ssh_exec_command (Host, the User, password, cmd, timeout = 10 ): "" " Use ssh to connect to remote server to execute the command : param host: host name : param user: user name : param password: password : param cmd: command execution : param seconds: timeout (default), must be of type int : return: dict "" " Result = { ' Status ' :. 1, ' Data ' : None} # return a result the try : SSH = paramiko.SSHClient () #Create a new instance of SSHClient ssh.banner_timeout = timeout # set host key, if the relevant information is not stored in the "known_hosts" in, SSHClient default behavior is to deny access, you will be prompted yes / NO ssh.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) ssh.connect (Host, 22 is, User, password, timeout = timeout) # connect to a remote server, one second timeout stdin, stdout, stderr = ssh.exec_command (cmd, get_pty = True, timeout = timeout) # Run out = stdout.readlines () # execution result, readlines returns a list of # execution state, 0 for success, 1 for failure Channel = stdout.channel status = channel.recv_exit_status () ssh.close () # Close ssh connection # returns the modified result Result [ ' Status ' ] = Status Result [ ' Data ' ] = OUT return Result the except Exception AS E: Print (E) Print ( " error log server failed IP:! {} " . the format (Host)) return False IF the __name__ == ' __main__ ' : Host = ' 192.168.10.1 ' User ='xiao' password = 'xiao@1234' cmd = "cat /etc/issue | awk '{print $1,$2,$3}'" res = ssh_exec_command(host, user, password, cmd) # print(res) if not res or not res['data'] or res['status'] != 0: print("错误, ip: {} 执行命令: {} 失败".format(host, cmd), "red") Exit () value = RES [ ' Data ' ] [0] .strip () # get the actual value Print ( " operating system:% S " % value)
Perform output:
Operating system: Ubuntu 16.04.2 LTS
Fifth, the error highlights
1. EllipticCurvePublicKey.public_bytes
Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.
the reason
paramiko 2.4.2 rely on cryptography, but the latest cryptography == 2.5 has some deprecated API.
solve
Deleted cryptography, installing 2.4.2, the error will not.
pip uninstall cryptography pip install cryptography==2.4.2
This article reference links:
https://blog.51cto.com/wangfeng7399/2376115
2. Error reading SSH protocol banner
Traceback (most recent call last): File "/python3/lib/python3.5/site-packages/paramiko/transport.py", line 1966, in run self._check_banner() File "/python3/lib/python3.5/site-packages/paramiko/transport.py", line 2143, in _check_banner "Error reading SSH protocol banner" + str(e) paramiko.ssh_exception.SSHException: Error reading SSH protocol banner Error reading SSH protocol banner
To solve this problem, paramiko responses need to wait a long time to adjust.
Modify paramiko / transport.py file
self.banner_timeout
Value, set it to 300 or other long value can solve this problem.
Reference:
- StackOverflow
- Tencent cloud
https://blog.csdn.net/qq_30513141/article/details/78201078
This article reference links:
https://blog.csdn.net/Temanm/article/details/50607741