python判断远程文件是否存在

2021/02/07 10:42
阅读数 2.1K

 

如果打印ok,则表示存在

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")

print(stdout.read())
client.close()

 

在有些情况下,你要测试文件是否存在于远程Linux服务器的某个目录下(例如:/var/run/test_daemon.pid),而无需登录到远程服务器进行交互。例如,你可能希望你的脚本根据特定文件是否存在的远程服务器上而由不同的行为。 

在本教程中,我将向您展示如何使用不同的脚本语言(如:Bash shell,Perl,Python)查看远程文件是否存在。 

这里描述的方法将使用ssh访问远程主机。您首先需要启用无密码的ssh登录到远程主机,这样您的脚本可以在非交互式的批处理模式访问远程主机。您还需要确保ssh登录文件有读权限检查。假设你已经完成了这两个步骤,您可以编写脚本就像下面的例子

使用bash判断文件是否存在于远程服务器上

 

#!/bin/bash


ssh_host="xmodulo@remote_server"

file="/var/run/test.pid"


if ssh $ssh_host test -e $file;

then echo $file exists

else echo $file does not exist

fi
  1.  


使用perl判断文件是否存在于远程服务器上

 

#!/usr/bin/perl
 
my $ssh_host = "xmodulo@remote_server";
my $file = "/var/run/test.pid";
 
system "ssh", $ssh_host, "test", "-e", $file;
my $rc = $? >> 8;
if ($rc) {
    print "$file doesn't exist\n";
} else {
    print "$file exists\n";
}


使用python判断文件是否存在于远程服务器上

#!/usr/bin/python

import subprocess

import pipes

ssh_host = 'xmodulo@remote_server'
file = '/var/run/test.pid'

resp = subprocess.call(
['ssh', ssh_host, 'test -e ' + pipes.quote(file)])
if resp == 0:

print ('%s exists' % file)
else:
print ('%s does not exist' % file)

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部