使用 pexpect 模块可以在 Python 中执行命令并检查其输出。你可以使用 ssh 命令连接到远程服务器,并执行 ls 命令检查文件是否存在。下面我就列举几个我经常遇到的几个错误并做个详细的解决方案。
1、问题背景
用户需要编写一个 Python 脚本,以检查一个文件是否存在于另一台计算机上,该计算机可以通过 SSH 访问。用户已经使用 pexpect 库编写了大部分代码,但需要捕获文件存在与否的值,以便断言文件是否存在。
2、解决方案
提出了以下三种解决方案:
方案 1:检查 SSH 命令的返回码
方案 2:使用 Paramiko SSH2 模块
方案 3:使用 pexpect 库
任何一种方案都能够解决用户的问题,即检查一个文件是否存在于另一台计算机上,该计算机可以通过 SSH 访问。用户可以选择一种最适合自己情况的方案。
代码例子
方案 1 的代码示例:
import subprocess
def check_file_exists(host, file_path):
command = f"ssh {host} test -f {file_path}"
result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
return True
elif result.returncode == 1:
return False
else:
raise Exception("SSH connection error or host not found.")
if __name__ == "__main__":
host = "10.10.0.0"
file_path = "/opt/ad/bin/email_tidyup.sh"
if check_file_exists(host, file_path):
print("File exists.")
else:
print("File does not exist.")方案 2 的代码示例:
import paramiko
def check_file_exists(host, username, password, file_path):
try:
transport = paramiko.Transport((host, 22))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.stat(file_path)
return True
except IOError:
return False
finally:
transport.close()
if __name__ == "__main__":
host = "10.10.0.0"
username = "service"
password = "word"
file_path = "/opt/ad/bin/email_tidyup.sh"
if check_file_exists(host, username, password, file_path):
print("File exists.")
else:
print("File does not exist.")方案 3 的代码示例:
import pexpect
def check_file_exists(host, username, password, file_path):
ssh = pexpect.spawn('ssh %s@%s' % (username, host))
ssh.expect('password:')
ssh.sendline(password)
ssh.expect('> ')
ssh.sendline('[ ! -e %s ] && echo NO || echo YES' % file_path)
ssh.expect(['NO', 'YES'])
if ssh.after == 'YES':
return True
else:
return False
if __name__ == "__main__":
host = "10.10.0.0"
username = "service"
password = "word"
file_path = "/opt/ad/bin/email_tidyup.sh"
if check_file_exists(host, username, password, file_path):
print("File exists.")
else:
print("File does not exist.")请确保替换示例代码中的 hostname、username、password 和 file_path 为实际的值。这段代码会通过 SSH 连接到远程服务器,并执行 ls 命令来检查文件是否存在
如果有啥问题可以这里留言讨论。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。