通过paramiko运行命令/删除文件夹

时间:2019-08-19 11:41:08

标签: python bash sftp paramiko

我无法运行某些命令。例如,rm或rmdir。

我正在尝试通过paramiko删除文件夹,但显示“找不到命令”。但是“ ls -l”命令可以正常工作。 bash脚本也可以正常工作。

key = paramiko.RSAKey.from_private_key_file(RSA_KEY)

with paramiko.SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(pkey=key, **SERVER_CONN)

    command = "rm /home/request_files/temp/*"

    in_, out_, err_ = client.exec_command(command=command)
    for i in out_:
        print(i)

“找不到命令”

key = paramiko.RSAKey.from_private_key_file(RSA_KEY)

with paramiko.SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(pkey=key, **SERVER_CONN)

    command = "ls"

    in_, out_, err_ = client.exec_command(command=command)
    for i in out_:
        print(i)

dir1

dir2

dir3

我还有一个bash脚本,可以正常工作:

sftp -P ${SERVER_PORT} ${SERVER_USERNAME}@${SERVER_HOST} <<EOF
    rm ${dir1}/*
    rmdir ${dir1}
EOF

1 个答案:

答案 0 :(得分:1)

感谢@martyn我找到了解决该问题的方法

def open_sftp(files_folder_name):
    key = paramiko.RSAKey.from_private_key_file(RSA_KEY)

    with paramiko.SSHClient() as client:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(pkey=key, **SERVER_CONN)
        with client.open_sftp() as sftp:
            files = sftp.listdir(path=files_folder_name)
            for f in files:
                sftp.remove(f"{files_folder_name}/{f}")
            sftp.rmdir(files_folder_name)