依赖 | 版本 |
---|---|
Python | 3.8 |
paramiko | 3.5.1 |
Ubuntu | 64bit |
使用paramiko实现SSH远程主机登录。
pip install paramiko
①通过ssh.exec_command直接执行cmd
import paramiko
import datetime
import os
# 配置项
remote_host = "x.x.x.x"
remote_user = "youruser"
remote_password = "yourpassword"
file_path = "/data/test.log"
def check_file_consistency():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(remote_host, username=remote_user, password=remote_password)
print(f"✅ 连接成功: {remote_host}")
# 使用md5命令校验文件一致性
compress_cmd = f"md5sum {file_path}"
sh.exec_command(compress_cmd)
output = shell.recv(1024).decode()
print(f"✅ 输出内容:{output}")
except Exception as e:
print(f"❌ 出错: {e}")
finally:
ssh.close()
# 执行函数
check_file_consistency(file_path)
②使用invoke_shell执行cmd
当我们执行特定命令或脚本,在Ubuntu系统中单独配置了账号和密码,在执行某些特定命令时需要使用sudo权限。在提交命令后需要自动输入密码。我们这里使用的invoke_shell,类似于开启了一个虚拟的shell命令行,来帮模拟我们手动执行命令的操作。
import paramiko
import datetime
import os
# 配置项
remote_host = "x.x.x.x"
remote_user = "youruser"
remote_password = "yourpassword"
remote_log_dir = "/data/test.log"
def check_file_consistency(file_path):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
file_full_path = get_file_path() + get_file()
try:
ssh.connect(remote_host, port=remote_port, username=remote_user, password=remote_password)
print(f"✅ 登录成功: {remote_host}")
# 启动交互式 shell
shell = ssh.invoke_shell()
time.sleep(2)
shell.recv(1024)
# 要执行的命令
command = f'sudo md5sum {file_path}\n'
# 发送命令
shell.send(command)
# 等待命令执行完成
time.sleep(3)
shell.send(remote_password + '\n')
time.sleep(2)
# 获取返回值
output = shell.recv(1024).decode()
print(f"✅ 输出内容:{output}")
except paramiko.AuthenticationException as e:
print("❌ 认证失败:", e)
except Exception as e:
print(f"❌ 出错: {e}")
finally:
ssh.close()
# 执行函数
check_file_consistency(file_path)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。