Python /创建ssh连接并更改文件

时间:2014-11-27 13:39:24

标签: python ssh

我在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中)

我找不到使用pxssh API的方法。我怎么能这样做。

1 个答案:

答案 0 :(得分:1)

在下面的代码中,我假设您已通过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  

希望这有帮助。