0

I am logging into a box and grep'ing a file content and printing to a file. I can print the grep'ed text but I am not able to print the host name to the file.

import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/Documents/privatekey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("connecting")
c.connect( hostname = "10.224.58.214", username = "ec2-user", pkey = k )
print ("connected")
commands = [ "grep jdbc /usr/share/activemq/conf/activemq.xml" ]
for command in commands:
    #print ("Executing {0}".format( command ))
    stdin , stdout, stderr = c.exec_command(command)
    print (hostname,file=open("output.csv", "a"))
    print (stdout.read(),file=open("output.csv", "a"))
    #print("Errors")
    #print (stderr.read())
c.close()

The line print (hostname,file=open("output.csv", "a")) is erroring out saying hostname is not defined.

lebelinoz
  • 4,890
  • 10
  • 33
  • 56

1 Answers1

1

hostname is not a defined variable, it's a named argument to c.connect() method. Define the missing variable in the beginning of your script. Below I used h:

import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/Documents/privatekey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("connecting")
h = "10.224.58.214"
c.connect( hostname = h, username = "ec2-user", pkey = k )
print ("connected")
commands = [ "grep jdbc /usr/share/activemq/conf/activemq.xml" ]
for command in commands:
    stdin , stdout, stderr = c.exec_command(command)
    print (h, file=open("output.csv", "a"))
    print (stdout.read(), file=open("output.csv", "a"))
c.close()
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • You are a saviour. Thanks a bunch. Its printing in a new line though , Can I print in the same line ? – sorabh sarupria Mar 18 '18 at 20:19
  • @sorabhsarupria this might depend on your python version, check this quesiton: https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space – Karol Dowbecki Mar 18 '18 at 20:25