2

I am a newbie in python. Recently there was a need for me to execute some remote commands in python. SO I started with first connecting to the server. I thought I would execute the command after I successfully connect to the remote server. But I am facing a strange(in the sense that I am not getting any help by googling the error) problem here.

I connect to the server manually by giving user and password.

> ssh root@atvtsXXXX -X
root@atvtsXXXX's password:
Last login: Thu Jul  9 10:05:37 2015 from 150.132.42.67
[root@atvtsXXXX ~]#

So you can see above that i am able to connect to the server manually using ssh. I heard that paramica is the module in python which can be used for connecting to a remote server and execute the commands.So I have written a small test script to first just connect.

> cat test.py
import paramiko
ssh = paramiko.SSHClient()
ssh.connect('atvtsXXXX', username='root',
    password='XXXXXX')
>

But when I execute the script I get the below error:

> python test.py
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    password='XXXXXX')
  File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 277, in connect
    socket.getaddrinfo(hostname, port):
socket.gaierror: [Errno -2] Name or service not known
>

As I am new, I don't understand much with this error. Could anybody please help. After I successfully connect to the server using this script I need to execute a command on the server and then get the output and print it on the console.

Below are the modules installed in my server:

>>> help('modules')

Please wait a moment while I gather a list of all available modules...

ANSI                collections         linuxfirewall_extension sanapilib
BaseHTTPServer      colorsys            linuxfirewall_plugin sanapilog
Bastion             commands            litp                sanapitest
CDROM               compileall          litpcli             sched
CGIHTTPServer       compiler            locale              screen
Cheetah             configmanager_plugin logging             select
ConfigParser        configmanagerapi_extension logrotate_extension selinux
Cookie              contextlib          logrotate_plugin    semanage
Crypto              cookielib           lxml                seobject
DLFCN               copy                macpath             sepolgen
DocXMLRPCServer     copy_reg            macurl2path         serializer
FSM                 createrepo          mailbox             service_plugin
HTMLParser          crypt               mailcap             setools
IN                  csv                 markdown            sets
IPy                 ctypes              markupbase          setuptools
M2Crypto            curl                marshal             sgmllib
MimeWriter          curses              math                sha
OpenSSL             datetime            md5                 shelve
Queue               dateutil            mhlib               shlex
SimpleHTTPServer    dbhash              mimetools           shutil
SimpleXMLRPCServer  dbm                 mimetypes           signal
SocketServer        dbus                mimify              simplejson
StringIO            dbus_bindings       mmap                singleton
TYPES               decimal             modeldeployment_extension site
UserDict            deltarpm            modeldeployment_plugin smtpd
UserList            dhcpservice_extension modulefinder        smtplib
UserString          dhcpservice_plugin  multifile           snack
_LWPCookieJar       difflib             multiprocessing     sndhdr
_MozillaCookieJar   dircache            mutex               socket
__builtin__         dis                 mysql_extension     sos
__future__          distutils           mysql_plugin        spwd
_abcoll             dl                  nas_extension       sqlite3
_ast                dmidecode           nas_plugin          sqlitecachec
_audit              dmidecodemod        naslib              sre
_bisect             dnsclient_extension netaddr             sre_compile
_bsddb              dnsclient_plugin    netrc               sre_constants
_bytesio            doctest             network_extension   sre_parse
_codecs             dot_parser          network_plugin      ssl
_codecs_cn          dps_plugin          new                 stat
_codecs_hk          drv_libxml2         nis                 statvfs
_codecs_iso2022     dsextras            nntplib             string
_codecs_jp          dumbdbm             ntp_extension       stringold
_codecs_kr          dummy_thread        ntp_plugin          stringprep
_codecs_tw          dummy_threading     ntpath              strop
_collections        easy_install        nturl2path          struct
_crypt              elasticsearch_extension numbers             subprocess
_csv                elasticsearch_plugin opcode              sunau
_ctypes             email               opendj_extension    sunaudio
_curses             encodings           opendj_plugin       symbol
_curses_panel       errno               operator            symtable
_dbus_bindings      ethtool             optparse            sys
_dbus_glib_bindings exceptions          os                  syslog
_deltarpm           fcntl               os2emxpath          sysparams_extension
_elementtree        fdpexpect           ossaudiodev         sysparams_plugin
_fileio             filecmp             package_extension   tabnanny
_functools          fileinput           package_plugin      tarfile
_hashlib            fnmatch             pam                 telnetlib
_heapq              formatter           paramiko            tempfile
_hotshot            fpformat            parser              termios
_json               fractions           pdb                 test
_locale             ftplib              pexpect             textwrap
_lsprof             functools           pickle              this
_multibytecodec     future_builtins     pickletools         thread
_multiprocessing    gc                  pipes               threading
_random             gdbm                pkg_resources       time
_semanage           genericpath         pkgutil             timeit
_snack              getopt              platform            timing
_socket             getpass             plistlib            toaiff
_sqlite3            gettext             policycoreutils     token
_sqlitecache        gio                 popen2              tokenize
_sre                glib                poplib              trace
_ssl                glob                posix               traceback
_strptime           gluster             posixfile           tty
_struct             gobject             posixpath           types
_symtable           gpgme               postgresql_extension unicodedata
_threading_local    groupapi_extension  postgresql_plugin   unittest
_warnings           groupplugin_plugin  pprint              urlgrabber
_weakref            grp                 profile             urllib
_yaml               gudev               pstats              urllib2
abc                 gzip                pty                 urlparse
aifc                hashlib             pwd                 user
anydbm              heapq               pxssh               userapi_extension
argparse            hmac                py_compile          userplugin_plugin
array               hosts_extension     pyclbr              uu
ast                 hosts_plugin        pycurl              uuid
asynchat            hotshot             pydoc               vcs_extension
asyncore            htmlentitydefs      pydoc_topics        vcsplugin
atexit              htmllib             pydot               versantmanagement_extension
audiodev            httplib             pyexpat             versantmanagement_plugin
audioop             idlelib             pygments            virtconv
audit               ihooks              pygraph             virtinst
auparse             imageop             pygtk               vnx1api
base64              imaplib             pyparsing           vnx2api
bdb                 imghdr              quopri              vnxcommonapi
binascii            imp                 random              vnxparser
binhex              imputil             re                  volmgr_extension
bisect              iniparse            readline            volmgr_plugin
bmc_extension       inspect             redhat_support_lib  warnings
bootmgr_extension   io                  redhat_support_tool wave
bootmgr_plugin      ipmi_plugin         repr                weakref
bsddb               itertools           resource            webbrowser
bz2                 json                rexec               whichdb
cPickle             jsonpath            rfc822              wsgiref
cProfile            jsonpickle          rhn                 xdrlib
cStringIO           keyword             rhsm                xml
calendar            koan                rlcompleter         xmllib
cba_extension       lib2to3             robotparser         xmlrpclib
cgi                 libvirt             routes              xxsubtype
cgitb               libvirt_extension   rpm                 yaml
cherrypy            libvirt_plugin      rpmUtils            yum
chunk               libvirt_qemu        runpy               yum_extension
cmath               libvirtmod          san_extension       yum_plugin
cmd                 libvirtmod_qemu     san_plugin          yumutils
cobbler             libxml2             sanapi              zipfile
code                libxml2mod          sanapicfg           zipimport
codecs              linecache           sanapiexception     zlib
codeop              linuxaudiodev       sanapiinfo
7
  • Here is a strange thing. Your error says line 5, but there are only 4 lines. Commented Jul 9, 2015 at 9:43
  • paramiko.org/installing.html Paramiko has two hard dependencies: the pure-Python ECDSA module ecdsa, and the PyCrypto C extension Have you installed these? Commented Jul 9, 2015 at 9:47
  • Did you install paramiko via pip? Commented Jul 9, 2015 at 9:55
  • depending on what you are trying to achieve, fabfile.org or ansible.com/home may come in handy... Commented Jul 9, 2015 at 9:56
  • @Rishav.. I dont know about that . these are the server that were given to us for doing the development tasks. Commented Jul 9, 2015 at 9:59

2 Answers 2

0

Recently there was a need for me to execute some remote commands in python.

You can also put your .py file to the server you are connecting to and then ssh to to the same server and run your code there too. If it is useful for you:

$ scp yourScript.py [email protected]:/path/yourScript.py # copy file to the server
$ ssh [email protected] # connect to the server
$ python /path/yourScript.py # run your python script on the server
Sign up to request clarification or add additional context in comments.

4 Comments

Is this a joke :) . I want the output of the remote command in the server and with with the output I have to perform some more operations.
@user1939168 What makes you think that you cannot do these?
And how can i get the output of the script in the first server from where I copied the script?
@user1939168 Why not write to a file, and scp again?
-1

way 1: use ip address instead of domain name like atvtsXXXX , maybe the paramiko package have something wrong with domain lookup. use this command to find the ip address

$nslookup atvtsXXXX 

way 2: I recommend you use pexpect to do this, pexpect called the SSH command of system ,it`s so easy to use.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.