繁体   English   中英

如何使用 Python Paramiko 重写 SSH 服务器上的文件内容?

[英]How to rewrite content of a file on SSH server with Python Paramiko?

我正在使用 Python Paramiko 连接到 SSH 服务器,我需要覆盖file的内容。 要写入文件的新内容位于new_content变量中。 我怎样才能做到这一点?

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=secret, port=port, look_for_keys=False)

new_content = 'content'


def sendCommand(comand):
    print("Sending command")

    if (client):
        stdin, stdout, stderr = client.exec_command(comand)

        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                alldata = stdout.channel.recv(1024)
                while stdout.channel.recv_ready():
                    alldata += stdout.channel.recv(1024)

                print(str(alldata, "utf8"))

sendCommand('export PATH="${HOME}/.fuelup/bin:${PATH}" && mkdir fuel-project && cd fuel-project && forc new counter-contract')

之后我打开要重写的file

sendCommand('vim counter-contract/src/main.sw')

结果我用这个方法解决了问题

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=secret, port=port, look_for_keys=False)

new_content = 'content'

    ftp = ssh.open_sftp()
    my_file = ftp.file('/root/path/to/file', 'w')  # 'w' will open the file for editing - it will truncate whatever was there before
    my_file.write(f'{new_content}') # write whatever you wish to the file
    my_file.flush()
    ftp.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM