且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

验证文件是否存在通过ssh

更新时间:2023-11-29 15:29:52

如果服务器接受SFTP会话,我不会理会Pexpect的,而是使用的的paramiko SSH2模块的Python:

If the server accepts sftp sessions, I wouldn't bother with pexpect, but instead use the paramiko SSH2 module for Python:

import paramiko
transport=paramiko.Transport("10.10.0.0")
transport.connect(username="service",password="word")
sftp=paramiko.SFTPClient.from_transport(transport)
filestat=sftp.stat("/opt/ad/bin/email_tidyup.sh")

在code打开一个 SFTPClient 连接在服务器上,您可以使用stat()来检查文件和目录是否存在等。

The code opens an SFTPClient connection to the server, on which you can use stat() to check for the existance of files and directories.

sftp.stat将引发IOError异常('没有这样的文件),当文件不存在。

sftp.stat will raise an IOError ('No such file') when the file doesn't exist.

如果服务器不支持SFTP,这会工作:

If the server doesn't support sftp, this would work:

import paramiko
client=paramiko.SSHClient()
client.load_system_host_keys()
client.connect("10.10.0.0",username="service",password="word")
_,stdout,_=client.exec_command("[ -f /opt/ad/bin/email_tidyup.sh ] && echo OK")
assert stdout.read()

SSHClient.exec_command返回三(标准输入,标准输出,标准错误)。在这里,我们只是检查任何输出的presence。你可能会有所不同,而不是命令或检查标准错误的任何错误消息来代替。

SSHClient.exec_command returns a triple (stdin,stdout,stderr). Here we just check for the presence of any output. You might instead vary the command or check stderr for any error messages instead.