python 远程修改服务器某用户的密码
如果是以非root用户登陆,前提该用户属于root组,以及在/etc/suders root ALL=(ALL) ALL 下面加入一行,把root改为你的用户名
# coding:utf8
import paramiko
import time
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hostname = '176.122.***.***'
port=29243
username = 'wangwh'
password = 'wangwh'
new_password = '*******'
s.connect(hostname=hostname, port=port, username=username, password=password)
cmd = 'passwd wangwh'
stdin, stdout, stderr = s.exec_command('sudo -S %s\n' % cmd)
stdin.write('%s\n' % password)
time.sleep(1)
stdin.write('%s\n' % new_password)
time.sleep(1)
stdin.write('%s\n' % new_password)
stdin.flush()
# or 或者用下面这个方法
stdin, stdout, stderr = s.exec_command('(echo \"%s\"; sleep 1.5; echo \"%s\"; sleep 1.5; echo \"%s\" ) | sudo -S %s\n' % (password, new_password,new_password,cmd))
# stdin.write('%s\n' % password)
# time.sleep(1)
# stdin.write('%s\n' % new_password)
# time.sleep(1)
# stdin.write('%s\n' % new_password)
# stdin.flush()
out = stdout.readlines()
print(out)
# [u'Changing password for user wangwh.\n', u'passwd: all authentication tokens updated successfully.\n']