#将射频仪器中的log日志解压复制带window中
import paramiko
import os
def ssh_execute_commands(host, port, username, password, commands):
# 创建一个SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(host, port, username, password)
# 串联所有命令为一个字符串,使用;作为分隔符
command_str = '; '.join(commands)
# 执行命令
stdin, stdout, stderr = ssh.exec_command(command_str)
# 获取命令输出
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
# 关闭连接
ssh.close()
# 返回输出和错误信息
return output, error
def ssh_transfer_files(host, port, username, password, remote_path, local_base_path):
# 创建一个SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(host, port, username, password)
# 使用SFTP客户端
sftp = ssh.open_sftp()
# 获取当前脚本运行的目录
local_base_path = os.path.dirname(os.path.abspath(__file__))
log_path = os.path.join(local_base_path, 'log')
# 检查log文件夹是否存在,不存在则创建
if not os.path.exists(log_path):
os.makedirs(log_path)
print(f"Created log directory at {log_path}")
# 遍历远程目录
for filename in sftp.listdir(remote_path):
remote_file_path = os.path.join(remote_path, filename)
local_file_path = os.path.join(log_path, filename)
# 检查log文件夹是否存在,不存在则创建
if not os.path.exists(local_file_path):
os.makedirs(local_file_path)
print(f"Created log directory at {local_file_path}")
# 下载文件到本地log目录
sftp.get(remote_file_path, local_file_path)
print(f"Transferred {remote_file_path} to {local_file_path}")
# 关闭SFTP和SSH连接
sftp.close()
ssh.close()
if __name__ == "__main__":
SSH_HOST = '172.168.9.87'
SSH_PORT = 22
SSH_USER = 'root'
SSH_PASSWORD = 'root'
REMOTE_PATH = '/forlinx/app'
# 注意:这里不再需要LOCAL_PATH,因为我们会使用脚本运行目录作为基础路径
ssh_transfer_files(SSH_HOST, SSH_PORT, SSH_USER, SSH_PASSWORD, REMOTE_PATH, '') # 传递空字符串,将在函数内部确定本地路径
COMMANDS = [
'ls', # 删除了cd,因为使用了绝对路径
]
output, error = ssh_execute_commands(SSH_HOST, SSH_PORT, SSH_USER, SSH_PASSWORD, COMMANDS)