Network Programming--import--socket--telnet

Source: Internet
Author: User
Tags echo d tableau server

--************************************************************************************************************* *******************

--import------Import Telnet Module---python network programming----------------------------------------------------------------------------

--************************************************************************************************************* *******************

--12.4-------------Import------Import Socket Module-------------Python Network Programming-----------------------------------------------------------------

Python provides two levels of access to network services. :

The low-level network service supports the basic socket, which provides the standard BSD Sockets API to access all the methods of the underlying operating system socket interface.

The high-level Network Service module, Socketserver, provides a server-centric class that simplifies the development of network servers.

What is a Socket?

A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.

--socket () function

Socket.socket ([family[, type[, Proto]]) creating sockets

Family: The socket family can make Af_unix or af_inet

Type: The socket type can be divided into sock_stream or sock_dgram depending on whether it is connection-oriented or non-connected

Protocol: General does not fill the default is 0.

Socket object (built-in) method

function Description

Server-side sockets

S.bind () binds the address (host,port) to the socket and, under Af_inet, represents the address in the form of a tuple (host,port).

S.listen () starts TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.

S.accept () passively accepts TCP client connections, (blocking) waits for a connection to arrive

Client sockets

S.connect () actively initializes the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.

Extended version ofthe S.CONNECT_EX () connect () function, which returns an error code instead of throwing an exception when an error occurs

Socket functions for public use

S.RECV () receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.

S.send () sends the TCP data, sending the data in the string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.

S.sendall () sends TCP data in full and sends TCP data in full. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.

S.recvfrom () receives UDP data, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.

S.sendto () sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), and specifies the remote address. The return value is the number of bytes sent.

S.close () close socket

S.getpeername () returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).

S.getsockname () returns the socket's own address. Typically a tuple (ipaddr,port)

S.setsockopt (level,optname,value) Sets the value of the given socket option.

S.getsockopt (Level,optname[.buflen]) Returns the value of the socket option.

S.settimeout (timeout) sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())

S.gettimeout () Returns the value of the current timeout, in seconds, or none if the timeout period is not set.

S.fileno () returns the file descriptor of the socket.

S.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to block mode (the default). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.

S.makefile () Create a file associated with the socket

--Service side

We use the socket function of the socket module to create a socket object. The socket object can set up a socket service by calling other functions.

We can now specify port (port) of the service by invoking the BIND (hostname) function.

Next, we call the Accept method of the socket object. The method waits for the client to connect and returns a Connection object that indicates that the client is connected.

The complete code is as follows:

#!/usr/bin/python

#-*-Coding:utf-8-*-

# File Name: server.py

Import Socket # Importing Socket module

s = Socket.socket () # Create socket Object

Host = Socket.gethostname () # Gets the local host name

Port = 12345 # setting ports

S.bind ((host, Port)) # bound Port

S.listen (5) # Waiting for client to connect

While True:

C, addr = S.accept () # establishes a client connection.

print ' Connection address: ', addr

C.send (' Welcome to Novice Tutorial! ')

C.close () # Close connection

--Client

Next we write a simple client instance that connects to the service created above. The port number is 12345.

The Socket.connect (Hosname, Port) method opens a TCP connection to a service provider that hosts a port of hostname. After the connection we can start from the service end of the data, remember that the operation will need to close the connection after completion.

The complete code is as follows:

#!/usr/bin/python

#-*-Coding:utf-8-*-

# File Name: client.py

Import Socket # Importing Socket module

s = Socket.socket () # Create socket Object

Host = Socket.gethostname () # Gets the local host name

Port = 12345 # setting Ports good

S.connect ((host, Port))

Print S.RECV (1024)

S.close ()

$ Python server.py Now we open two terminals, the first terminal executes the server.py file:

$ python client.py The second terminal executes the client.py file:

Welcome to the Novice Tutorial!

This is when we open the first terminal, we will see the following information output:

Connection address: (' 192.168.0.118 ', 62461)

Python Internet module (some important modules of Python network programming)

--12.4-------------Import------Import httplib module------urllib module------XMLRPCLIB module------Port number:------HTTP Web Access

--12.4-------------Import------Import nntplib module------port number: 119------NNTP Read and post news articles, commonly known as "posts"

--12.4-------------Import------Import telnetlib module------port number:------Telnet command line

Discover that you must "\ r \ n" When sending commands in the Windows operating system, otherwise the command cannot be recognized

#-*-CODING:GBK-*-

Import Sys

Import Telnetlib

Import time;

HOST = "192.168.1.103"

USER = B "Administrator"

PASS = B "1"

Cmd=b "dir rn" #此处也可以为ipconfig

TN = Telnetlib. Telnet (HOST)

Tn.set_debuglevel (0);

Print ("Loading file, please wait ..."); #输出结果 loading the file, please wait a moment ...

Time.sleep (5) #休眠5秒, or the second reading may not be readable.

Tn.read_until (b "Login:") #当匹配到login时代表已成功连接到HOST主机, here to enter the account hint

Tn.write (user+b "RN") #向主机发送登陆帐号, analog keyboard input

#print ("Login Success");

Tn.read_until (b "Password:") #向主机发送登陆密码, analog keyboard input

Tn.write (pass+b "RN")

#print ("password Success");

Tn.read_until (b "Microsoft Telnet Server") #判断是否成功登陆主机

Tn.write (cmd+b "RN") #向主机发送相应的DOS命令行

#print ("cmd success");

Tn.write (b "exitrn")

Ra=tn.read_all () #读取所匹配到的数据

#print (Type (RA));

Print (Ra.decode (' GBK '));

Tn.close ()

Print ("Get end ...");


The following is a script for Mizuhayashi

#-*-coding:utf-8-*-

Import Telnetlib

Import Sys

Import logging

Import time

def telnetdo (Host=none,user=none,pass=none,command=none):

Tn=telnetlib. Telnet ()

Tn.open (host,port=23,timeout=10)

Tn.read_until ("Login:")

Tn.write (user+ ' \ r \ n ')

Tn.read_until ("Password:")

Tn.write (pass+ ' \ r \ n ')

Tn.read_until (">")

If ' in HOST ':

print ' Enter ' +host

I=0

While I<len (COMMAND):

if (i==1):

#print ' Enter I=1 '

Start_copy (Tn,command,i)

Else

Tn.write (command[i]+ ' \ r \ n ')

Aa=tn.read_until (">")

Print I

#print aa.decode (' Utf-8 '). Encode (' Utf-8 ')

I=i+1

Else

print ' Enter ' +host

For comm in COMMAND:

print ' Jin ru l ' +comm

Tn.write (comm+ ' \ r \ n ')

Aa=tn.read_until (">")

Print Aa.decode (' gb2312 '). Encode (' Utf-8 ')

Tn.write (' exit\r\n ')

Tn.close ()


def start_copy (tn,command,i):

Tn.write (command[i]+ ' \ r \ n ')

Res=tn.read_until (">")

Winres=res.decode (' Utf-8 '). Encode (' Utf-8 ') # ' \xe5\xb7\xb2\xe5\xae\x8c\xe6\x88\x90 '

Print Winres

Succon= ' Backup written '

If Succon in Winres: #9

print ' Success '

Tn.write (' exit\r\n ')

Tn.close ()

Else

print ' fail '

Tn.write (' exit\r\n ')

Tn.close ()

Sys.exit (1)


Def get_workbook ():

Logpre=time.strftime ('%y-%m-%d ', Time.localtime (Time.time ()))

command170=[' CD c:\\program Files\\tableau\\tableau Server\\10.4\\bin ',

' Tabadmin backup d:\\tableaubak\\tableauserverbakup–v-d ']

command181=[' CD c:\\program Files\\tableau\\tableau Server\\10.4\\bin ',

' Echo d|xcopy/e/y \\\\21.64.160.170\\tableaubak\\tableauserverbakup-' +logpre+ '. Tsbak D:\\tableaubak ',

' Tabadmin restore d:\\tableaubak\\tableauserverbakup-' +logpre+ '. Tsbak ']

Telnetdo (' 21.64.160.170 ', ' Administrator ', ' Sherpa6209 ', command170)

Telnetdo (' 21.64.160.181 ', ' Administrator ', ' Sherpa6209 ', command181)


# logpre=time.strftime ('%y%m%d ', Time.localtime (Time.time ()))

# loggerfile= '/home/hadoop/aboutpython/shellpy/tellog/tableau ' +logpre+ '. Log '


If __name__== ' __main__ ':

Get_workbook ()


--12.4-------------Import------Import ftplib module------port number:------urllib module------FTP File transfer

--12.4-------------Import------Import gopherlib module------URLLIB module------Port number:------Gopher Information Lookup


Network Programming--import--socket--telnet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.