Thursday, October 30, 2014

Python script to run remote SSH commands with sudo permission

I created a Python script to run remote SSH command with sudo permission. Linux SSH command doesn’t support password as command option, you have to use expect script to connect to multiple servers for automation. plink tool in Windows support password as command option.
The trick to accept sudo password is ‘-S’ option in sudo, which accept sudo password piped from stdin.It seems to be safe, I turned on debug and I couldn’t see the password recorded in secure/messages logs.
There are two versions of the script: the command line one and the class/module one.

The command line version.

if the clear text password is an concern, you can wrap the script by getpasswd module in Python,which read password from stdin.Read password once and apply the password to multiple servers.
[root@~]# ./  -s server1 -u admin -p Passwd123 date
Thu Oct 30 15:36:27 EST 2014

#'service sshd status' command  ran successfully with sudo enabled '-t'
[root@~]# ./  -t -s server1 -u admin -p Passwd123  'service sshd status'
openssh-daemon (pid  15686) is running...

#!/usr/bin/env python
import sys
import paramiko
import argparse
import socket
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--servername", help="hostname or IP", required=True)
parser.add_argument("-P", "--port", help="ssh port default=22", default=22)
parser.add_argument("-t", "--sudo", help="enable sudo,sudo password will use the value of --password",action='store_true')
parser.add_argument("cmd",help="command to run")

host = args.servername
port = args.port
user = args.username 
password = args.password
cmd = args.cmd
if args.sudo:
    fullcmd="echo " + password + " |   sudo -S -p '' " + cmd

#if __name__ == "__main__":
client = paramiko.SSHClient()
#Don't use host key auto add policy for production servers
except (socket.error,paramiko.AuthenticationException) as message:
    print "ERROR: SSH connection to "+host+" failed: " +str(message)
if args.sudo: 
stdout = session.makefile('rb', -1)

The  class version

The class version allow multiple commands to run in an existing SSH transport,which is more efficient.To use the class,copy to a folder and create a new script to import the class 'from pyssh import PySSH',then reference the code in MAIN section without if statement.
#!/usr/bin/env python
import sys
import socket
import paramiko
# Class: PySSH
class PySSH(object):
    def __init__ (self):
        self.ssh = None
        self.transport = None  

    def disconnect (self):
        if self.transport is not None:
        if self.ssh is not None:

    def connect(self,hostname,username,password,port=22):
        self.hostname = hostname
        self.username = username
        self.password = password

        self.ssh = paramiko.SSHClient()
        #Don't use host key auto add policy for production servers
        except (socket.error,paramiko.AuthenticationException) as message:
            print "ERROR: SSH connection to "+self.hostname+" failed: " +str(message)
        return  self.transport is not None

    def runcmd(self,cmd,sudoenabled=False):
        if sudoenabled:
            fullcmd="echo " + self.password + " |   sudo -S -p '' " + cmd
        if self.transport is None:
            return "ERROR: connection was not established"
        #print "fullcmd ==== "+fullcmd
        if sudoenabled:
        stdout = session.makefile('rb', -1)
        return output

if __name__ == '__main__':
    hostname = 'server1'
    username = 'admin'
    password = 'password123'
    ssh = PySSH()
    print output
    output=ssh.runcmd('service sshd status',True)
    print output


  1. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

    iOS Training in Chennai

    1. IEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.

      IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.

      corporate training in chennai corporate training in chennai

      corporate training companies in india corporate training companies in india

      corporate training companies in chennai corporate training companies in chennai

      I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai

  2. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic. Android App Development Company in Chennai

  3. your information is really awesome as well as it is very excellent and i got more interesting information from your blog. Security Mobile alerts Chennai

  4. Great post! I am see the great contents and step by step read really nice information.I am gather this concepts and more information. It's helpful for me my friend. Also great blog here with all of the valuable information you have.
    Python Training in Chennai

  5. Interesting blog which attracted me more.I hope you will post more update like this.
    Digital marketing company in Chennai

  6. This comment has been removed by a blog administrator.

  7. you are posting such a new idea is very interesting and give updates.
    msbi training in chennai

  8. your post conveys a good messages and interesting things and give more updates.
    digital marketing company in india

  9. Thank you so much for your post. That's amazing !

  10. This comment has been removed by a blog administrator.

  11. But I am not able to execute cd /var/log/ as a command. It gives error like cd not found

  12. Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.
    website designing company

  13. nice topic which you have choose.
    second is, the information which you have provided is better then other blog.
    so nice work keep it up. And thanks for sharing.
    Tourist visa services Dwarka

  14. I’m planning to start my blog soon, but I’m a little lost on everything. Would you suggest starting with a free platform like Word Press or go for a paid option? There are so many choices out there that I’m completely confused. Any suggestions? Thanks a lot.
    Best AWS Training in Marathahalli | AWS Training in Marathahalli
    Amazon Web Services Training in Anna Nagar, Chennai |Best AWS Training in Anna Nagar, Chennai

  15. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.
    python training Course in chennai | python training in Bangalore | Python training institute in kalyan nagar

  16. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Devops Training courses
    Devops Training in Bangalore
    Best Devops Training in pune
    Devops interview questions and answers

  17. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Java training in Chennai | Java training in Bangalore

    Java online training | Java training in Pune

  18. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa interview questions and answers
    automation anywhere interview questions and answers
    blueprism interview questions and answers
    uipath interview questions and answers
    rpa training in chennai

  19. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.
    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai

  20. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 

    best rpa training in chennai | rpa online training |
    rpa training in chennai |
    rpa training in bangalore
    rpa training in pune
    rpa training in marathahalli
    rpa training in btm


  21. Such a wonderful article on AWS. I think its the best information on AWS on internet today. Its always helpful when you are searching information on such an important topic like AWS and you found such a wonderful article on AWS with full information.Requesting you to keep posting such a wonderful article on other topics too.
    Thanks and regards,
    AWS training in chennai
    aws course in chennai what is the qualification
    aws authorized training partner in chennai
    aws certification exam centers in chennai
    aws course fees details
    aws training in Omr

  22. Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

  23. All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.
    python training in chennai
    python course in chennai
    python training in bangalore

  24. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

    Data Science training in rajaji nagar | Data Science Training in Bangalore
    Data Science with Python training in chennai
    Data Science training in electronic city
    Data Science training in USA
    Data science training in pune

  25. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore
    rpa online training

  26. Very nice post. I definitely appreciate this site. Thanks for sharing...visit for
    web development company in noida

  27. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Best Devops online Training
    Online DevOps Certification Course - Gangboard

  28. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    AWS Training in Bangalore |Best AWS Training Institute in Bangalore BTM, Marathahalli
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR

  29. Very Clear Explanation. Thank you to share this
    Devops Training Institute in Chennai

  30. Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this.angular 4 training in chennai | angularjs training in omr | best angularjs training institute in chennai | angularjs training in omr

  31. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

  32. I would really like to read some personal experiences like the way, you've explained through the above article. I'm glad for your achievements and would probably like to see much more in the near future. Thanks for share.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

  33. Learn Digital Academy offers, Digital marketing offers, Digital Marketing Course in Bangalore.
    practically on Live Projects.

  34. Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up! Kindly visit us @Luxury Boxes
    Premium Packaging
    Luxury Candles Box
    Earphone Packaging Box
    Wireless Headphone Box
    Innovative Packaging Boxes
    Wedding gift box
    Leather Bag Packaging Box
    Cosmetics Packaging Box
    Luxury Chocolate Boxes

  35. Thanks for sharing nice information with us. I like your post and all you share with us is up to date and quite informative,

    Cpa offers

  36. For Devops Training in Bangalore - Devops Training in Bangalore

  37. For Hadoop Training in Bangalore Visit : HadoopTraining in Bangalore

  38. This is a very informative content, I appreciate that author has taken time for research and content writing. Thanks
    Website designing company in Delhi

  39. Ignou Project offer free assistance and help to students in how to write their respective course project report and synopsis. We provide Project of MBA, MAPC, MSC DFSM, PGDRD, PGDDM, MAEDU, MARD,MPA, MPS, MTM, AHE,BTS, AMT and DNHE.

  40. Hello Admin!

    Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today..

  41. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

    Digital marketing courses in Bangalore