如何使用Python Paramiko(SSHClient)检查远程文件是否可写?

1 投票
1 回答
1114 浏览
提问于 2025-04-16 12:26

我正在尝试使用paramiko来检查一个远程文件是否可以写入。我的代码是

from paramiko.ssh_exception import SSHException, BadHostKeyException 
import paramiko
import sys
from optparse import OptionParser
import os

stdin, stdout, stderr = self.__econnection.exec_command('bash');
stdin.write('if [ -w "%s" ];'%(temp_path))
stdin.write("then echo True;");
stdin.write("else echo False;");
stdin.write("fi;");
stdin.flush();

但是一执行这些代码,终端就卡住了,我不得不关闭它。请帮帮我..

1 个回答

2

假设你有一个叫做 ssh 的 Paramiko SSHClient 对象,temp_path 是你要测试的文件的路径,而且连接已经设置好了,可以试试下面的代码:

# prepare command
command = 'if [ -w {filename} ]; then echo True; else echo False; fi;'
# add filename
command = command.format(filename=temp_path)
# execute command
stdin, stdout, stderr = ssh.exec_command(command)
# read the result from stdout and remove the trailing newline character
result = stdout.readline().rstrip()
print(result)

撰写回答