python 使用 fabric 上传与下载文件
#!/home/peng/pyCode/env/study/bin/python3.10
from fabric import Connection
import argparse
import logging
from colorama import init, Fore, Style
# 初始化Colorama
init()
# 创建一个logger对象
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 创建一个控制台输出的handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# 创建一个格式化器
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# 将格式化器添加到控制台输出的handler中
console_handler.setFormatter(formatter)
# 将控制台输出的handler添加到logger中
logger.addHandler(console_handler)
# 添加颜色
logging.addLevelName(logging.DEBUG, f"{Fore.BLUE}{logging.getLevelName(logging.DEBUG)}{Style.RESET_ALL}")
logging.addLevelName(logging.INFO, f"{Fore.GREEN}{logging.getLevelName(logging.INFO)}{Style.RESET_ALL}")
logging.addLevelName(logging.WARNING, f"{Fore.YELLOW}{logging.getLevelName(logging.WARNING)}{Style.RESET_ALL}")
logging.addLevelName(logging.ERROR, f"{Fore.RED}{logging.getLevelName(logging.ERROR)}{Style.RESET_ALL}")
logging.addLevelName(logging.CRITICAL, f"{Fore.RED}{logging.getLevelName(logging.CRITICAL)}{Style.RESET_ALL}")
# 传入ip地址,执行远程操作
def new_connection(ip):
return Connection(host=ip, user="peng", connect_kwargs={"password": "peng"})
class Conn:
def __init__(self, c: Connection):
self.c = c
def run(self, cmd):
logging.info(f"run cmd is {cmd}")
return self.c.run(cmd)
def up_file(self, local_file_path, remote_path):
logging.info(f"copy local_file: {local_file_path} to {remote_path}")
return self.c.put(local_file_path, remote_path)
def down_file(self, remote_file_path):
logging.info(f"donw_file from {remote_file_path} to_local_file ./tmp/")
self.c.get(remote=remote_file_path, local="./tmp/")
parser = argparse.ArgumentParser(description="输入IP地址,执行远程操作")
parser.add_argument("--ip", help="远程ip地址", required=True)
args = parser.parse_args()
if __name__ == "__main__":
# 创建连接
c = new_connection(args.ip)
conn = Conn(c=c)
# 将当前目录下的文件,上传到远程文件
conn.up_file("./aa.txt", "/home/peng/")
# 将远端文件下载下载到本地
conn.down_file("/home/peng/scapy_zd.py")
直接运行 ./main.py --ip 192.168.220.150
即可。