通过ssh验证文件是否存在

chr*_*ley 5 python testing ssh bash pexpect

我试图使用pexpect测试SSH上是否存在文件.我有大部分代码工作,但我需要捕获值,所以我可以断言文件是否存在.我所做的代码如下:

def VersionID():

        ssh_newkey = 'Are you sure you want to continue connecting'
        # my ssh command line
        p=pexpect.spawn('ssh service@10.10.0.0')

        i=p.expect([ssh_newkey,'password:',pexpect.EOF])
        if i==0:
            p.sendline('yes')
            i=p.expect([ssh_newkey,'password:',pexpect.EOF])
        if i==1:
            p.sendline("word")
            i=p.expect('service@main-:')
            p.sendline("cd /opt/ad/bin")
            i=p.expect('service@main-:')
            p.sendline('[ -f email_tidyup.sh ] && echo "File exists" || echo "File does not exists"')
            i=p.expect('File Exists')
            i=p.expect('service@main-:')
            assert True
        elif i==2:
            print "I either got key or connection timeout"
            assert False

        results = p.before # print out the result

VersionID()
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Mik*_*eyB 9

为什么不利用命令的返回码通过SSH传回的事实呢?

$ ssh victory 'test -f .bash_history'
$ echo $?
0
$ ssh victory 'test -f .csh_history'
$ echo $?
1
$ ssh hostdoesntexist 'test -f .csh_history'
ssh: Could not resolve hostname hostdoesntexist: Name or service not known
$ echo $?
255
Run Code Online (Sandbox Code Playgroud)

这样,您只需检查返回代码,而无需捕获输出.


fli*_*ght 4

如果服务器接受 sftp 会话,我就不会使用 pexpect,而是使用Python 的paramiko SSH2 模块:

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")
Run Code Online (Sandbox Code Playgroud)

该代码打开与服务器的SFTPClient连接,您可以在该连接上使用 stat() 检查文件和目录是否存在。

当文件不存在时,sftp.stat 将引发 IOError(“没有这样的文件”)。

如果服务器不支持 sftp,则可以使用以下方法:

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()
Run Code Online (Sandbox Code Playgroud)

SSHClient.exec_command 返回一个三元组(stdin、stdout、stderr)。这里我们只检查是否存在任何输出。您可以更改命令或检查 stderr 是否有任何错误消息。