我想运行 ssh 而不要求输入密码,并在没有密码的情况下调用 systemctl,我尝试执行以下操作:
ssh -t <user>@<host> "echo <password> | sudo -S systemctl status kubelet"
和:
sshpass -p '$<password>' ssh -t -o 'StrictHostKeyChecking=no' <user>@<host> 'sudo service kubelet restart
还:
echo <password> | ssh -tt <user>@<host> "sudo service kubelet restart"
我将用户添加到 sudoers 中,并且能够在没有密码的情况下运行 systemctl,上面的所有命令都要求输入密码,但以下命令除外:
sshpass -p '$<password>' ssh -t -o 'StrictHostKeyChecking=no' <user>@<host> 'sudo service kubelet restart
它没有给我任何提示并且看起来它起作用了但什么也没做。
答案1
sshpass 仅传递 ssh 连接的密码。但是您的“sudo service kubelet restart”命令本身会单独要求输入 sudo 密码。您的 systemctl status 命令不需要 sudo 权限,这就是它通过的原因。请尝试这样做:
sshpass -p '$<password>' ssh -t -o 'StrictHostKeyChecking=no' <user>@<host> "echo <password> | sudo -S service kubelet restart"
答案2
我使用 python3 来解决此问题,虽然不太优雅,但它确实有效(这不是完整的脚本,只是相关部分)。
initiate_restart = [
"echo <password> | sudo -S systemctl restart kubelet",
"echo <password> | sudo -S systemctl restart docker",
]
node = paramiko.SSHClient()
print(node)
node.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
node.connect(hostname=get_ip, username=user_name, password=node_pass)
with open("/tmp/reset_log.log", "a") as f:
f.write(date + ' Restarting ' + 'Node-' + get_ip + "\n")
except:
print("[!] Cannot connect to the SSH Server")
with open("/tmp/reset_log.log", "a") as f:
f.write(date + ' Could not connect to' + ' Node-' + get_ip + "\n")
exit()
for command in initiate_restart:
print("="*50, command, "="*50)
stdin, stdout, stderr = node.exec_command(command)
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print(err)