我是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中的一个模块,它可以用来连接到远程服务器并执行commands.So,我写了一个小测试脚本来首先连接。
> 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发布于 2015-07-09 17:43:32
最近我需要在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发布于 2015-07-09 17:56:19
方式一:使用ip地址,而不是像atvtsXXXX那样的域名,可能paramiko包的域名查找有问题。使用此命令查找ip地址
$nslookup atvtsXXXX 方法2:我推荐你使用pexpect来做这件事,pexpect被称为系统的SSH命令,它非常容易使用。
https://stackoverflow.com/questions/31313608
复制相似问题