标签:下载 begin file dir linu ble net fabric use
最近这段时间,经常通过xftp在服务器上创建目录并上传文件,繁琐的事一直循环的做,因此一直在想通过Python脚本能自动创建目录,上传文件,询问公司大佬和百度终于找到了方法,接下来看看。
主要安装两个模块paramiko与scp,功能即可实现
paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。
scp是我们在shell上经常使用的命令,用来远程传输文件。python上也能做到scp的功能
# coding:utf-8 import paramiko from scp import SCPClient class Host: def __init__(self): self.user = "" self.ip = "root" self.password = "123456" # 创建目录 def mkdir(self): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.ip, username=self.user, password=self.password) sftp = ssh.open_sftp() sftp.mkdir("/data/etc/bill/20200224") print("Create folder ‘20200224‘ in remote hosts successfully!\n") ssh.close() except: print("Create folder failure!\n") def upload_img(self,img_name, remote_path="/data/etc/bill/20200224", file_path="D:\PythonProject\img"): ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy) ssh_client.connect(self.ip, username=self.user, password=self.password) scpclient = SCPClient(ssh_client.get_transport(), socket_timeout=15.0) local_path = file_path + "\\" + img_name try: scpclient.put(local_path, remote_path) except FileNotFoundError as e: print(e) print("系统找不到指定文件" + local_path) else: print("文件上传成功") ssh_client.close() if __name__ == ‘__main__‘: t = Host print("Begin......\n") t.mkdir() img_name = 1.jpg upload_img( img_name)
标签:下载 begin file dir linu ble net fabric use
原文地址:https://www.cnblogs.com/mtfan01/p/12360006.html