Python/创建ssh连接并更改fi

2024-06-17 09:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了以下代码:

import pxssh
s = pxssh.pxssh()
try:
  if not s.login ('x.x.x.x', 'root', 'password'):
      print "SSH session failed on login."
      print str(s)
  else:
      print "SSH session login successful"
      s.sendline ('uptime')
      s.prompt()         # match the prompt
      print s.before     # print everything before the prompt.
      s.logout()
except pxssh.ExceptionPxssh, e:
   print "SSH conection failed"
   print str(e)

我成功地连接了ssh。在

现在,我想向系统中已经存在的文件追加一个密钥(在/root/.ssh/authorized_keys

我找不到任何方法来使用pxsshAPI来完成它。我怎么做呢。在


Tags: the代码importsessionloginrootsshprompt
1条回答
网友
1楼 · 发布于 2024-06-17 09:14:14

在下面的代码中,我假设您已经通过ssh成功地连接到远程机器。我使用这种方法的目的类似,但数据不同。在

file_data = open("/root/.ssh/authorized_keys").read()
"""manipulate the contents of the file such that the variable new_key contains
   the data you want to append to the file via ssh"""

#I'll assume the data to be abcd
new_key = "abcd"                 
#Constructing the command to pass via ssh
cmd = 'echo "' + new_key + '">>/root/.ssh/authorized_keys'
#note that I've used >> and not >, the former will append while the later will overwrite the file
#also the path given in the above command is the one on the remote ssh server and not your local machine
s.sendline(cmd)
s.prompt()
print s.before
#voilà your key is appended to the file on the remote server
#you can check that
s.sendline("cat /root/.ssh/authorized_keys")
s.prompt()
print s.before  

希望这有帮助。在

相关问题 更多 >