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")