通过python使用脚本中的密码将ssh连接到远程计算机

2024-04-25 00:18:32 发布

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

我在用遥控器工作。每次需要验证文件更新时间时,我都必须使用ssh,而且有多个脚本将对远程计算机执行ssh。 我上网查了一下,但按我的要求找不到。

我试图找到一个使用ssh的python脚本,脚本中也有密码,因为我的python脚本将每5分钟检查一次文件修改次数,并且每次脚本执行时我都不能输入密码。 我从SO和internet上尝试了这些代码,但无法满足我的需要。 Establish ssh session by giving password using script in python

How to execute a process remotely using python

另外,我通过ssh简单地进入一个远程机器,然后我尝试ssh,但是通过python脚本进入另一个远程机器cox,这个python脚本还包括检查不同文件修改时间的代码。。意味着我已经ssh到一台远程机器,然后我想从那里运行一些python脚本,检查另一台远程机器上文件的文件修改时间。 在python脚本中有没有一种简单的ssh远程机器和密码的方法。 我将不胜感激。


Tags: 文件代码脚本机器密码远程so计算机
2条回答

在这里添加我的程序,它依赖于用户密码并显示不同输出文件的状态。

#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()

#Check the login
def check_hostname(host_name, pw_r):
    with locke1:
        print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
        file_output = open('output_file','a')
        file_success = open('success_file','a')
        file_failed = open('failed_file','a')
        file_error = open('error_file','a')
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
          ssh.connect(host_name, username='root', password=pw_r, timeout=5)
          #print ("Success")
          file_success.write(str(host_name+"\n"))
          file_success.close()
          file_output.write("success: "+str(host_name+"\n"))
          file_output.close()

          # printing output if required from remote machine
          #stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
          #for line in stdout.readlines():
           # print (line.strip())

        except paramiko.SSHException:
                # print ("error")
                file_failed.write(str(host_name+"\n"))
                file_failed.close()
                file_output.write("failed: "+str(host_name+"\n"))
                file_output.close()
                #quit()
        except paramiko.ssh_exception.NoValidConnectionsError:
                #print ("might be windows------------")
                file_output.write("failed: " + str(host_name + "\n"))
                file_output.close()
                file_failed.write(str(host_name+"\n"))
                file_failed.close()
                #quit()
        except socket.gaierror:
          #print ("wrong hostname/dns************")
          file_output.write("error: "+str(host_name+"\n"))
          file_output.close()
          file_error.write(str(host_name + "\n"))
          file_error.close()

        except socket.timeout:
           #print ("No Ping %%%%%%%%%%%%")
           file_output.write("error: "+str(host_name+"\n"))
           file_output.close()
           file_error.write(str(host_name + "\n"))
           file_error.close()

        ssh.close()


def performer1():
    while True:
        hostname_value = q.get()
        check_hostname(hostname_value,pw_sent)
        q.task_done()

if __name__ == '__main__':

    print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")

    f = open('output_file', 'w')
    f.write("-------Output of all hosts-------\n")
    f.close()
    f = open('success_file', 'w')
    f.write("-------Success hosts-------\n")
    f.close()
    f = open('failed_file', 'w')
    f.write("-------Failed hosts-------\n")
    f.close()
    f = open('error_file', 'w')
    f.write("-------Hosts with error-------\n")
    f.close()

    with open("input_file") as f:
        hostname1 = f.read().splitlines()

#Read the standard password from the user
    pw_sent=getpass.getpass("Enter the Password:")
    start_time1 = time.time()

    for i in hostname1:
        q.put(i)
    #print ("all the hostname : "+str(list(q.queue)))
    for no_of_threads in range(10):
        t = threading.Thread(target=performer1)
        t.daemon=True
        t.start()

    q.join()
    print ("Check output files for results")
    print ("completed task in" + str(time.time()-start_time1) + "seconds")

如果你想试试paramiko模块。下面是一个工作的python脚本示例。

import paramiko

def start_connection():
    u_name = 'root'
    pswd = ''
    port = 22
    r_ip = '198.x.x.x'
    sec_key = '/mycert.ppk'

    myconn = paramiko.SSHClient()
    myconn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    my_rsa_key = paramiko.RSAKey.from_private_key_file(sec_key)

    session = myconn.connect(r_ip, username =u_name, password=pswd, port=port,pkey=my_rsa_key)

    remote_cmd = 'ifconfig'
    (stdin, stdout, stderr) = myconn.exec_command(remote_cmd)
    print("{}".format(stdout.read()))
    print("{}".format(type(myconn)))
    print("Options available to deal with the connectios are many like\n{}".format(dir(myconn)))
    myconn.close()


if __name__ == '__main__':
    start_connection()

相关问题 更多 >