通过sftp以用户身份以root用户身份和基于ssh的身份验证来编辑文件会产生IOError:[Errno 13]权限被拒绝错误

时间:2019-07-17 04:53:22

标签: python sftp paramiko

我遇到IOError:[Errno 13]使用基于SSH的身份验证时尝试使用用户root编辑文件时,权限被拒绝错误。我在做什么错了?

try:
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(hostname, username=userName, key_filename=keyFile)
  print "Connection succesfully established ... "
except paramiko.AuthenticationException,e:
  print "Could not connect to %s" % hostname

def changepwd():
  sftp_client = ssh.open_sftp()
  fname = '/etc/ssh/sshd_config'
  with sftp_client.open(fname, 'r+') as f:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r'PasswordAuthentication no', 'PasswordAuthentication yes', data))
    f.close()
  os.system("service sshd restart")
  sftp_client.close()
  ssh.close()

错误:

    with sftp_client.open(fname, 'r+') as f:
  File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 372, in open
    t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 813, in _request
    return self._read_response(num)
  File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 865, in _read_response
    self._convert_status(msg)
  File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 896, in _convert_status
    raise IOError(errno.EACCES, text)
IOError: [Errno 13] Permission denied

1 个答案:

答案 0 :(得分:0)

谢谢大家的答复。我最终直接使用了exec_command,效果很好。

stdin, stdout, stderr = ssh.exec_command("sed -i -e 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config")