1
\$\begingroup\$

I wrote script to install public key of my system to remote host. I had tested the script it is working fine for me. script take data like IP password and ssh port form CVS file. I do not want to use import os. only use CSV and paramiko imports. My aim is to copy public key to my remote host.

import csv
import os

from paramiko import SSHClient, AuthenticationException, AutoAddPolicy

username = "root"
key = open(os.path.expanduser('~/.ssh/id_rsa.pub')).read()

with open("hostinfo.csv") as h:
    host = csv.reader(h, delimiter=",")
    for i in host:
        # csv file field ip,pass,port
        HostIP, HostPass, HostPort = i[0], i[1], i[2]
        try:
            client = SSHClient()
            client.load_system_host_keys()  
            client.set_missing_host_key_policy(AutoAddPolicy)  
            client.connect(HostIP, HostPort, username, HostPass)
            print("Running commands on {0} port {1}".format(HostIP, HostPort))
            client.exec_command('mkdir -p ~/.ssh/')
            client.exec_command('echo "%s" >> ~/.ssh/authorized_keys' % key)
            client.exec_command('chmod 644 ~/.ssh/authorized_keys')
            client.exec_command('chmod 700 ~/.ssh/')
            print("Key is installed in {0}".format(HostIP))
        except AuthenticationException:
            raise AuthenticationException('Authentication failed: did you remember to create an SSH key?')
        finally:
            client.close()
            print("connection is closed")
\$\endgroup\$
11
  • 1
    \$\begingroup\$ Any reason you can't use ssh-copy-id? It would copy over the public key to the server you desire. \$\endgroup\$
    – Zchpyvr
    Dec 26, 2019 at 0:22
  • \$\begingroup\$ If I want to install public key in 2000 servers then can I use ssh-copy-id and type password or export data to CSV then use script and Wait for output \$\endgroup\$
    – jay sonar
    Dec 26, 2019 at 17:09
  • \$\begingroup\$ What data are you collecting? I had assumed all you wanted to do was copy the public key to '2000' servers. Is there specific information you need from each time you copy the key over? \$\endgroup\$
    – Zchpyvr
    Dec 26, 2019 at 22:22
  • \$\begingroup\$ 2000 server is just for example ; my script is working but can you improve it. I not want os module to use in this script. Only CSV and paramiko I want.@zchpyvr \$\endgroup\$
    – jay sonar
    Dec 27, 2019 at 0:31
  • \$\begingroup\$ What I'm trying to say is that you don't need a Python script, there is already a well-written command-line utility for this exact scenario: ssh-copy-id. I recommend looking it up. \$\endgroup\$
    – Zchpyvr
    Dec 27, 2019 at 0:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.