python子进程远程查找-exec文件名,带空格
因此,我有一个远程Linux服务器,希望在本地计算机上运行Python脚本,列出远程服务器上特定文件夹中的所有文件及其修改日期。这就是我目前的代码:python子进程远程查找-exec文件名,带空格,python,python-3.x,linux,ssh,subprocess,Python,Python 3.x,Linux,Ssh,Subprocess,因此,我有一个远程Linux服务器,希望在本地计算机上运行Python脚本,列出远程服务器上特定文件夹中的所有文件及其修改日期。这就是我目前的代码: command = "find \""+to_directory+'''\"* -type f -exec sh -c \"stat -c \'%y:%n\' \'{}\'\" \;''' scp_process_ = subprocess.run("ssh "+to
command = "find \""+to_directory+'''\"* -type f -exec sh -c \"stat -c \'%y:%n\' \'{}\'\" \;'''
scp_process_ = subprocess.run("ssh "+to_user+"@"+to_host+" '"+command+"' ", shell=True, capture_output=False, text=True)
现在运行命令
find "/shares/Public/Datensicherung/"* -type f -exec sh -c "stat -c '%y:%n' '{}'" \;
在服务器上,它本身工作正常,没有任何错误
但是,一旦我使用子进程通过ssh远程运行它,它就遇到了一个问题:文件夹中有一个空格:“/shares/Public/Datensicherung/New folder/hi.txt”,其中有一个空格:
stat: can't stat '/shares/Public/Datensicherung/New': No such file or directory
stat: can't stat 'folder/hi.txt': No such file or directory
我知道这是一团糟,但这是我能建立的最好的解决方案。
我想继续使用subprocess和ssh,但如果您有更好的解决方案,请随时发布。有时出现问题是因为命令字符串格式错误。为了与Unix通信,shell被封装在模块中。因此,基本上您可以使用包装代码,然后将其传递到
supbroess.run
我看不到要调用的实际最终cmd,但您可以自己使用shlex.split
将其拆分为适当的命令
根据您的示例,它可能类似于:
from shlex import join
cmd = join(['ssh',
f'{to_user}@{to_host}',
'find',
f'{to_directory}*',
'-type',
'f',
'-exec',
'sh',
'-c',
"stat -c '%y:%n' '{}'",
';']))
scp_process_ = subprocess.run(cmd, shell=True, capture_output=False, text=True)
此外,您可能还需要使用
shell=True
选项。使用shell=True
您将调用三个shell实例,每个实例都需要一层引用。当然,这是可能的,但如果可能的话,有很多理由可以避免
首先,您可以很容易地避免本地shell=True
,这实际上提高了Python代码的健壮性和清晰性
command=“find\”“+to_directory+'''\'*-type f-exec sh-c\”stat-c\'%y:%n\'''{}\'\'”;''
scp_进程u=子进程.run(
[“ssh”,对_用户+“@”+对_主机,命令],
捕获(输出=假,文本=真)
其次,stat
可以很容易地接受多个参数,因此您也可以去掉sh-c'.'
command='find“+”to_directory+”-键入f-exec stat-c“%y:%n”{}+'
优化也会将+
切换为\代码>(因此,sh-c'
包装器是双重无用的)