python - 通过 ssh 验证文件是否存在

标签 python bash testing ssh 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()

感谢您的帮助。

最佳答案

为什么不利用命令的返回码通过 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

这样,您可以只检查返回码,而无需捕获输出。

关于python - 通过 ssh 验证文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2192442/

相关文章:

node.js - 使用 botium 和 testmybot 包测试聊天机器人

linux - 这个 bash 脚本有多危险?

c - 下面的 bash 程序调用做了什么?

bash - 如何从文件路径中提取目录路径?

python multiprocessing.Process.terminate - 如何杀死子进程

php - 未知方法 ApiTester::sendGet 与 Codeception

ruby-on-rails - 在 Controller 中使用 using 方法测试辅助方法

Python input() 函数无法正常运行 : doesn't seem to record any input. 也许是 Linux 问题?

python - 如何在 PyQt5 中更新窗口?

python - "' int ' object is not iterable"在 while