[英]How to rewrite content of a file on SSH server with Python Paramiko?
I am using Python Paramiko to connect to SSH server, I need to overwrite the contents of the file
.我正在使用 Python Paramiko 连接到 SSH 服务器,我需要覆盖
file
的内容。 The new content to write to the file is in the new_content
variable.要写入文件的新内容位于
new_content
变量中。 How can i do this?我怎样才能做到这一点?
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')
After that I open the file
to be rewritten:之后我打开要重写的
file
:
sendCommand('vim counter-contract/src/main.sw')
As a result, I solved the problem with this method结果我用这个方法解决了问题
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.