day8-套接字sock 實現SSH遠程執行命令功能

複習java

#面向對象編程
#類:
#對象
#實例化 :從一個類到產生一個對象的過程
    #對象 = 類名()   #__init__初始化方法,是爲了給一個具體的對象放一些初識的屬性
#在類中:
    # 靜態屬性 直接定義在類中的屬性,使用靜態屬性:類名、對象名均可以調用
    # 動態屬性 就是方法 就是定義在類中的函數 默認傳一個self
# class Person:
#     money = 100
# sister = Person()
# father = Person()
# Person.money += 200
# Person.money += 500
# print(Person.money)
#組合:是什麼有什麼的關係。
    #一個類的對象做爲兩外一個類的屬性來使用
#繼承
    #子類
    #父類、基類、超類
    #單繼承和多繼承
    #子類中出現 : 派生 父類中沒有的子類中有了
        #派生方法
        #派生屬性
    #經典類和新式類在多繼承上有什麼特色
        #新式類廣度優先和經典類深度優先

# python2 : 經典類 指名道姓去使用父類的方法

class A:
    def func(self):print('A')

class B(A):
    def func(self):
        super().func()
        # super(B,self).func()
        print('B')

b = B()
b.func()
super(B,b).func() #不經常使用python

 

多態linux

#初識面向對象
#繼承和組合
#面向對象的進階
#多態
#封裝
#面向對象:反射
#類中的內部的 雙下方法

#__init__
#__dict__

#多態:python自帶多態

# def func(int a):
#     print(a)

# func(2)
# func('ashkgask')

class Animal:
    pass

class Dog(Animal):pass
class Cat(Animal):pass

wangcai = Dog()
kitty = Cat()
def eat(obj):
    print(obj.name,'在吃')

eat(1)
eat('hello')

#多態:在其餘語言裏:類的繼承
      #在Python中

#有相同特色的類:鴨子類型
    #list 和 tuple  鴨子類型
    #1+2   'a'+'b'git

 

封裝面試

#封裝就是把方法和屬性 扔到一個容器裏裝起來
#私有的:只能在類的內部使用,不能直接在類的外部使用
# class Supermarket:
#     __DISCONT = 0.8  #加了雙下劃線就被定義成了一個私有的
#     def __init__(self,org_price):
#         self.price = org_price * Supermarket.__DISCONT
# A.__COUNTRY
# a = A()
# a.func()
# print(A.__dict__)
# print(A._A__COUNTRY)   #不合法

# class Goods:
#     __DISCONT = 0.8  #加了雙下劃線就被定義成了一個私有的
#     def __init__(self,org_price):
#         self.price = org_price * Goods.__DISCONT
#
# apple = Goods(10)
# print(apple.price)

# class A:
#     def __func(self):
#         self.__name = 'alex'
#
# a = A()
# a._A__func()

#私有的  __名字
#定義私有靜態屬性
#定義私有的方法
#定義私有的對象屬性
#只要是私有的:類內正常使用,類外不能直接使用。若是必定要用_類名__名字
#私有的東西能夠子類中使用麼?不能

#用到私有變量
    #1.當咱們想要隱藏一個變量不被外調用的時候
    #2.當咱們寫在父類中且不但願子類繼承的時候
class A:
    __B = 'hahaha'

class B(A):pass

print(A.__dict__)
print(B.__dict__)shell

 

幾個類中的裝飾器編程

#property
#classmethod
#staticmethod
# class Circle:
#     def __init__(self,r):
#         self.r = r
#
#     @property
#     def area(self):
#         return self.r *self.r *3.14
#
# c1 = Circle(5)
# print(c1.area)

class A:
    def __init__(self,name):
        self.__name = name
    @property
    def name(self):
        return self.__name
    @name.setter
    def name(self,new_name):
        if type(new_name) is str:
            self.__name = new_name

# a = A('alex')
# print(a.name)
# #但願不從外部被修改 因此設置一個私有的屬性
# #可是又但願能從外部查看 因此使用一個property
# a.name = 'alex_sb'
# print(a.name)

#classmethod
class A:
    country = 'China'
    def func(self):
        self.name= 'alex'

    @classmethod    #類方法:就是不須要傳具體的對象
                    #可是可使用類的屬性、靜態屬性
    def c_method(cls):
        print('in class method')
        print(cls.country)

    @staticmethod   #靜態方法
    def s_method():print('in static method')

A.c_method()
A.s_method()

#徹底的面向對象編程
#全部的方法代碼都必須寫類裏
#只能把原來的函數寫進類裏
#而本來又只是函數 因此就加上一個staticmethod裝飾器json

 

反射設計模式

#issubclass(子類,父類)
# class A:pass
# class B(A):pass
# print(issubclass(B,A))
# isinstance(對象,類名)
#判斷一個對象是否是這個類的實例
# b = B()
# print(isinstance(b,B))
# print(isinstance(b,A))

#什麼叫反射
#使用字符串的形式去獲取變量
# a = 1
# b = 2
# name = input('變量名 :')
# if name == 'a':
#     print(a)

class Person:
    role = 'Person'
    country = 'China'
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def func(self):
        print('%s in func'%self.name)
alex = Person('alex',80)
# name = input('屬性名 :')
# Person.role
# alex.name  alex.age
# if hasattr(alex,'func'):
#     func = getattr(alex,'func')
#     func()


def func2(self):
    print('%s in func2' % self.name)

#setattr
# alex.sex = None
# setattr(alex,'sex','不詳')
# print(alex.sex)
# setattr(alex,'func2',func2)  #setattr綁定方法是一個假的
# # print(alex.func)          # 在使用的時候必需要手動傳self對象
# alex.func2(alex)
#delattr
# delattr(alex,'name')  #del alex.name
# alex.name
#使用反射來調用類中的方法和屬性,對象的屬性


# import demo1
# print(demo1.a)
# print(getattr(demo1,'a'))
# demo1.qqxing()
# getattr(demo1,'qqxing')()

a = 'aaaaa'
import sys
this_module = sys.modules[__name__]
print(getattr(this_module,'a'))


#反射:a.b --> getattr(a,'b')
#hasattr getattr setattr delattr
#類,靜態屬性、類方法
#對象,方法、屬性
#模塊,函數,變量
#本模塊,函數,變量app

 

類中的內置方法

# class A:
#     def __call__(self, *args, **kwargs):
#         print('aaaaaaaa')

# a = A()()

#__new__
class A:
    def __init__(self):     #初始化方法
        self.x = 1
        print('in init function')
    def __new__(cls, *args, **kwargs):  #構造方法
        print('in new function')
        return object.__new__(A, *args, **kwargs)
a = A()   #先構造一個對象 再初始化屬性
#單例模式
#從頭至尾只有一個實例
class Singleton:
    # def __new__(cls, *args, **kw):
    #     if not hasattr(cls, '_instance'):
    #         cls._instance = object.__new__(A, *args, **kw)
    #     return cls._instance
    # def __str__(self):
    #     return 'singleton 的 實例'

    def __repr__(self):
        return 'singleton repr'
one = Singleton()
two = Singleton()
# print('%s'%one)
# two.a = 3
# print(one.a)
# print(id(one))
# print(id(two))
# print(one == two)
# print(one is two)

#面試的時候
#單例模式是一種設計模式
#設計模式早期只在java裏使用

# l = list()
# l.append(123)
# print(l)

# print('%r is somebody'%'alex')
# print('%s is somebody'%'alex')

#這個類有100個對象,只要name和sex相同,我就認爲是相同的對象
#要求對100個對象進行去重
class Person:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    def __hash__(self):
        return hash(self.name+self.sex)

    def __eq__(self, other):
        if self.name == other.name and self.sex == other.sex:return True


p_lst = []
for i in range(84):
    p_lst.append(Person('egon',i,'male'))

print(p_lst)
print(set(p_lst))

 

基於TCP協議的簡單套接字通訊

客戶端:

import socket

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#發起電話連接
phone.connect(('127.0.0.1',8080))


#發消息
phone.send('hello'.encode('utf-8'))

#收消息
data=phone.recv(1024)
print(data)

#關機
phone.close()

服務端

import socket

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#綁定手機卡
phone.bind(('127.0.0.1',8080))

#開機
phone.listen(5)

#等電話連接
print('starting...')
conn,client_addr=phone.accept() #(套接字連接,客戶端的ip和port)
print(conn)
# print(client_addr)

#收消息
data=conn.recv(1024) # 1024最大的限制
print('客戶端數據: ',data)

#發消息
conn.send(data.upper())

#掛電話
conn.close()

#關機
phone.close()

 

加上通訊循環和連接循環

服務端:

import socket

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議
# phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #就是它,在bind前加

#綁定手機卡
phone.bind(('127.0.0.1',8080))

#開機
phone.listen(5)

#等電話連接
print('starting...')
while True:
    conn,client_addr=phone.accept() #(套接字連接,客戶端的ip和port)
    print(client_addr)

    while True: #通訊循環
        #收消息
        try:
            data=conn.recv(1024) # 1024最大的限制
            print('客戶端數據: ',data)
            if not data:break #針對linux系統
            #發消息
            conn.send(data.upper())
        except ConnectionResetError:
            break

    #掛電話
    conn.close()

#關機
phone.close()

客戶端0

import socket

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#發起電話連接
phone.connect(('127.0.0.1',8080))


while True:
    #發消息
    msg=input('>>: ').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8'))
    print('has send====>')
    #收消息
    data=phone.recv(1024)
    print('has recv=====>')
    print(data.decode('utf-8'))

#關機
phone.close()









客戶端1

import socket

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#發起電話連接
phone.connect(('127.0.0.1',8080))


while True:
    #發消息
    msg=input('>>: ').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8'))
    print('has send====>')
    #收消息
    data=phone.recv(1024)
    print('has recv=====>')
    print(data.decode('utf-8'))

#關機
phone.close()









 

客戶端2

import socket

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#發起電話連接
phone.connect(('127.0.0.1',8080))


while True:
    #發消息
    msg=input('>>: ').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8'))
    print('has send====>')
    #收消息
    data=phone.recv(1024)
    print('has recv=====>')
    print(data.decode('utf-8'))

#關機
phone.close()









 

 

實現ssh遠程執行命令的功能(low版)

服務端:

import socket
import subprocess
import struct

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議
phone.bind(('127.0.0.1',8080))
phone.listen(5)

while True:
    conn,client_addr=phone.accept() #(套接字連接,客戶端的ip和port)
    print(client_addr)

    while True: #通訊循環
        #收消息
        try:
            cmd=conn.recv(1024) # 1024最大的限制
            if not cmd:break #針對linux系統

            #執行,拿到執行結果
            obj = subprocess.Popen(cmd.decode('gbk'), shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

            stdout_res=obj.stdout.read()
            stderr_res=obj.stderr.read()
            #先發報頭
            total_size=len(stderr_res)+len(stdout_res)
            conn.send(struct.pack('i',total_size))

            #再發真是的數據
            # conn.send(stdout_res+stderr_res)
            conn.send(stdout_res)
            conn.send(stderr_res)
        except ConnectionResetError:
            break

    #掛電話
    conn.close()

#關機
phone.close()

客戶端:

import socket
import struct

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#發起電話連接
phone.connect(('127.0.0.1',8080))


while True:
    #發消息
    cmd=input('>>: ').strip()
    if not cmd:continue
    phone.send(cmd.encode('gbk'))

    #先收報頭
    header_struct=phone.recv(4)
    total_size=struct.unpack('i',header_struct)[0]

    #再收消息
    cmd_res=b''
    recv_size=0
    while recv_size < total_size:
        recv_data=phone.recv(1024)
        cmd_res+=recv_data
        recv_size+=len(recv_data)

    print(cmd_res.decode('gbk'))

#關機
phone.close()









 

粘包

服務端1

from socket import *


server=socket(AF_INET,SOCK_STREAM)
server.bind(('127.0.0.1',8080))
server.listen()

conn,addr=server.accept()

data1=conn.recv(5)
print('data1:',data1)
data2=conn.recv(5)
print('data2:',data2)

 

客戶端1

from socket import *


client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))


client.send('hello'.encode('utf-8'))
# import time
# time.sleep(10)
client.send('world'.encode('utf-8'))

服務端2

from socket import *


server=socket(AF_INET,SOCK_STREAM)
server.bind(('127.0.0.1',8080))
server.listen()

conn,addr=server.accept()

data1=conn.recv(1)
print('data1:',data1)
import time
time.sleep(5)
data2=conn.recv(1024)
print('data2:',data2)

 

客戶端2

from socket import *


client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))


client.send('hello'.encode('utf-8'))
import time
time.sleep(3)
client.send('world'.encode('utf-8'))

 

實現ssh遠程執行命令的功能(最終版)

服務端:

import socket
import subprocess
import struct
import json

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議
phone.bind(('127.0.0.1',8080))
phone.listen(5)

while True:
    conn,client_addr=phone.accept() #(套接字連接,客戶端的ip和port)
    print(client_addr)

    while True: #通訊循環
        #收消息
        try:
            cmd=conn.recv(1024) # 1024最大的限制
            if not cmd:break #針對linux系統

            #執行,拿到執行結果
            obj = subprocess.Popen(cmd.decode('gbk'), shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)

            stdout_res=obj.stdout.read()
            stderr_res=obj.stderr.read()

            # 製做報頭
            header_dic = {
                'filename': 'a.txt',
                'total_size': len(stdout_res)+len(stderr_res),
                'md5': 'xxxxxxxxx'
            }
            head_json = json.dumps(header_dic)
            head_bytes = head_json.encode('utf-8')




            #先發報頭長度
            conn.send(struct.pack('i',len(head_bytes)))

            #先發報頭
            conn.send(head_bytes)

            #再發真是的數據
            # conn.send(stdout_res+stderr_res)
            conn.send(stdout_res)
            conn.send(stderr_res)
        except ConnectionResetError:
            break

    #掛電話
    conn.close()

#關機
phone.close()

 

客戶端:

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             import socket
import struct
import json

#買手機
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #SOCK_STREAM表明TCP協議

#發起電話連接
phone.connect(('127.0.0.1',8080))


while True:
    #發消息
    cmd=input('>>: ').strip()
    if not cmd:continue
    phone.send(cmd.encode('gbk'))

    #先收報頭長度
    struct_res=phone.recv(4)
    header_size=struct.unpack('i',struct_res)[0]

    #再收報頭
    head_bytes=phone.recv(header_size)
    head_json=head_bytes.decode('utf-8')
    head_dic=json.loads(head_json)
    print(head_dic)

    #最收消息
    cmd_res=b''
    recv_size=0
    total_size=head_dic['total_size']
    while recv_size < total_size:
        recv_data=phone.recv(1024)
        cmd_res+=recv_data
        recv_size+=len(recv_data)

    print(cmd_res.decode('gbk'))

#關機
phone.close()









 

異常處理try


print('====>1')
print('====>2')
print('====>3')
# l=[]
# l[1000000000000000000000000000000000000000000]
# d={}
# d['k']

age=input('>>: ').strip()
if age.isdigit():
    int(age)

print('====>4')
print('====>5')




print('====>6')

 

執行系統命令的模塊


# import os
#
# res=os.system('dir')
# print('命令的結果',res)


# import subprocess
#
# obj=subprocess.Popen('dir',shell=True,
#                      stdout=subprocess.PIPE,
#                      stderr=subprocess.PIPE)
#
#
#
# stdout_res1=obj.stdout.read()
# print(stdout_res1.decode('gbk'))

# stdout_res2=obj.stdout.read() #在第一次讀時,管道就空了
# print('========>',stdout_res2.decode('gbk'))




# import subprocess
#
# obj=subprocess.Popen('diasdfasdfasr',shell=True,
#                      stdout=subprocess.PIPE,
#                      stderr=subprocess.PIPE)



# stdout_res1=obj.stdout.read() #命令執行錯誤會把結果送到stderr管道
# print(stdout_res1.decode('gbk'))

# stdout_res2=obj.stderr.read() #命令執行錯誤會把結果送到stderr管道
# print(stdout_res2.decode('gbk'))





#ls ; pwasdfasdfd; echo 123
#ls && pwd && echo 123





#執行命令
# import subprocess
#
# obj=subprocess.Popen('tasklist | findstr pycharm',shell=True,
#                      stdout=subprocess.PIPE,
#                      stderr=subprocess.PIPE)
#
# print(obj.stdout.read().decode('gbk'))



import subprocess
obj1=subprocess.Popen('tasklist',shell=True,
                 stdout=subprocess.PIPE,)

obj2=subprocess.Popen('findstr pycharm',shell=True,
                     stdin=obj1.stdout,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)

print(obj2.stdout.read().decode('gbk'))

相關文章
相關標籤/搜索