Skip to main content
 首页 » 编程设计

python之使用python在远程服务器中执行命令

2025年05月04日9lonelyxmas

我是python新手。最近需要用python执行一些远程命令。所以我首先连接到服务器。我以为我会在成功连接到远程服务器后执行命令。 但是我在这里面临一个奇怪的问题(从某种意义上说,我没有通过谷歌搜索错误获得任何帮助)。

我通过提供用户名和密码手动连接到服务器。

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

所以你可以在上面看到我可以使用 ssh 手动连接到服务器。 我听说 paramica 是 python 中的模块,可用于连接到远程服务器并执行命令。所以我写了一个小测试脚本来首先连接。

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

但是当我执行脚本时,出现以下错误:

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

因为我是新手,所以我对这个错误不太了解。 有人可以帮忙吗?使用此脚本成功连接到服务器后,我需要在服务器上执行命令,然后获取输出并将其打印在控制台上。

以下是我服务器中安装的模块:

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

请您参考如下方法:

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

您还可以将您的 .py 文件放到您正在连接的服务器上,然后 ssh 到同一台服务器并在那里运行您的代码。如果对您有用:

$ scp yourScript.py username@server.com:/path/yourScript.py # copy file to the server 
$ ssh username@server.com # connect to the server 
$ python /path/yourScript.py # run your python script on the server