Paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令、文件传输等功能。
安装模块
默认Python没有自带,需要手动安装:
pip3 install paramiko
二、上传文件
#!/usr/bin/env python3 # coding: utf-8 import paramiko def sftp_upload_file(host,user,password,server_path, local_path,timeout=10): """ 上传文件,注意:不支持文件夹 :param host: 主机名 :param user: 用户名 :param password: 密码 :param server_path: 远程路径,比如:/home/sdn/tmp.txt :param local_path: 本地路径,比如:D:/text.txt :param timeout: 超时时间(默认),必须是int类型 :return: bool """ try: t = paramiko.Transport((host, 22)) 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
测试一下上传,完整代码如下:
#!/usr/bin/env python3 # coding: utf-8 import paramiko def sftp_upload_file(host, user, password, server_path, local_path, timeout=10): """ 上传文件,注意:不支持文件夹 :param host: 主机名 :param user: 用户名 :param password: 密码 :param server_path: 远程路径,比如:/home/sdn/tmp.txt :param local_path: 本地路径,比如:D:/text.txt :param timeout: 超时时间(默认),必须是int类型 :return: bool """ try: t = paramiko.Transport((host, 22)) 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, server_path, local_path) if not res: print("上传文件: %s 失败"%local_path) else: print("上传文件: %s 成功" % local_path)