반응형

출처: http://www.dreamy.pe.kr/zbxe/CodeClip/164988

 

한글로된 글이 없어서 우선 내가 알아낸 곳과 사용한 곳까지 작성을 해둘려고한다.

PARAMIKO

  • Python 2.6+, 3.3+에서 사용할 수 있는 SSHv2 구현체이다.
  • 물론 Client, Server를 둘다 사용이 가능하다.
  • 저 레벨 암호화를 위해서 PyCrypro(이부분은 Python C 확장으로 구현)를 제외한 나머지 부분들은 전부 Python으로만 구현되어있다.

사용

1. 사용 예제

1
2
3
4
import paramiko
 
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username='ujuc', password='lol')

2. Host Keys

  • 첫 접근시 받아오는 Host Keys가 있다. 이것을 받아서 저장하던 날려먹던 상관은 하지 않지만 있어야지 접근이 가능하다.
    • 처음 ssh로 접근시 무의식적으로 yes를 누르는 그것!!
  • 그러다보니 여기서도 그것에 관련된 내용을 사용할 수 있다.
  • set_missing_host_key_policy(policy)를 이용하여 host keys를 받아 저장할 것인지 아닌지를 판단하게 되는데. 기본값은 RejectPolicy로 되어있으며,yes를 받아와야한다면 AutoAddPolicy를 사용하도록 한다.
1
2
3
4
5
import paramiko
 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', username='ujuc', password='lol')
  • 물론 Public key를 이용해서 비밀번호 없이 접근이 가능하도록 할 수 있을듯 한데 그건 좀 확인이 필요할듯.

3. 실행

  • 실행 명령어 exec_command를 실행하게되면, 값을 3개를 tuple로 받아온다.
  • stdinstdoutstderr이다.
    *명령어에 대한 값들을 받아와 확인할때는 아래와 같이 작성을 하면된다.
1
2
3
stdin, stdout, stderr = ssh.exec_command()
stdout.readlines()
['test\n']
  • 만약 sudo명령어가 필요한 경우,
1
2
3
4
stdin, stdout, stderr = ssh.exec_command('sudo')
<span class="skimlinks-unlinked">stdin.write('lol\n</span>')
<span class="skimlinks-unlinked">stdin.flush</span>()
data = <span class="skimlinks-unlinked">stdout.read</span>()
  • 위와 같이하여 작성을 하도록 한다.
  • 그리고 write다음에는 flush를 꼭 해줘야 작동을 하니 그점은 주의하도록 한다. 관련 내용은 여기에 있다

4. 연결 끊기

  • 작업이 끝났으면 연결을 끊어야된다.
  • 그냥 close()를 불러오면 알아서 끊어준다.

5. SFTP 사용.

  • 어찌보면 ssh를 사용하면서 편했던 것이 sftp의 사용이다. 간단한 사용방법과ssh가 설치가되어있으면 따로 ftp를 생성하지 않더라도 간단한 파일을 주고 받을 수 있도록 되어있기 때문이다.
  • 먼저 ssh로 접속한 다음, open_sftp()후 파일을 가져올때는get('localfile.py', 'remotefile.py')를 이용하고, 올려둘때는put('localfile.py', 'remotefile.py')를 사용하면된다.

참고 자료

Paramiko Homepage
Docs paramiko
SSH Programming With Paramiko | Completely Different
Paramiko: SSH and SFTP With Python

반응형
반응형

출처: http://egloos.zum.com/rucaus/v/2424600


파이썬에서 어떤 클래스를 정의하고, 다른 파이썬 파일에서 그 클래스를 사용하고 싶다면 다음과 같이 코딩한다.

gameclass.py 에 어떤 캐릭터 스탯 클래스가 있다고 해보자.

class character_stat:
def __init__(self) :
self.m_hp = "0"
self.m_mp = "0"

def set_all( self, hp, mp) :
self.m_hp = hp
self.m_mp = mp
def print( self):
print "HP : ", self.m_hp
print "MP : ", self.m_mp


main.py에서는 아래와 같이 가져다 쓰면 된다.

import gameclass

instance = gameclass.character_stat()
instance.set_all( 100, 150)
instance.print()

실행하면 main.py는 HP : 100, MP : 150을 출력한다. 


반응형
반응형

출처: http://egloos.zum.com/pythondev/v/106115


# -*- coding: cp949 -*-
#!/usr/bin/python

# commondialogs.py

import wx
import os, sys


class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        
        self.CreateStatusBar()
        # 메뉴바 생성
        menuBar = wx.MenuBar()
        # 메뉴 추가
        menu = wx.Menu()
        menu.Append(99,  "&Message Dialog", "Shows a Message Dialog")
        menu.Append(100, "&Color Dialog", "Shows a Color Dialog")
        menu.Append(101, "&File Dialog", "Shows a File Dialog")
        menu.Append(102, "&Page Setup Dialog", "Shows a Page Setup Dialog")
        menu.Append(103, "&Font Dialog", "Shows a Font Dialog")
        menu.Append(104, "&Directory Dialog", "Shows a Directory Dialog")
        menu.Append(105, "&SingleChoice Dialog", "Shows a SingleChoice Dialog")
        menu.Append(106, "&TextEntry Dialog", "Shows a TextEntry Dialog")
        menuBar.Append(menu, "&Dialogs")
        # 프레임에 메뉴 셋팅
        self.SetMenuBar(menuBar)
        
        # 메뉴별 이벤트 함수 연결
        self.Bind(wx.EVT_MENU, self.message, id=99)
        self.Bind(wx.EVT_MENU, self.choosecolor, id=100)
        self.Bind(wx.EVT_MENU, self.openfile, id=101)
        self.Bind(wx.EVT_MENU, self.pagesetup, id=102)
        self.Bind(wx.EVT_MENU, self.choosefont, id=103)
        self.Bind(wx.EVT_MENU, self.opendir, id=104)
        self.Bind(wx.EVT_MENU, self.singlechoice, id=105)
        self.Bind(wx.EVT_MENU, self.textentry, id=106)


    # 메세지 다이얼 로그 띄우기
    def message(self, event):
        # 메시지 다이얼로그 생성(이벤트 처리기)
        dlg = wx.MessageDialog(self, 'To save one life is as if you have saved the world.', 'Talmud', wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()


    # 색상 다이얼 로그 띄우기(이벤트 처리기)
    def choosecolor(self, event):
        # 생상 다이얼로그 생성
        dlg = wx.ColourDialog(self)
        # 풀 색상 선택창 사용 유무 지정(True : 사용 / False : 미사용)
        dlg.GetColourData().SetChooseFull(False)
        # 색상 다이얼로그에서 색상을 선택후 ok 버튼을 누르면
        if dlg.ShowModal() == wx.ID_OK:
            # 선택한 색상값을 얻엄
            data = dlg.GetColourData()
            # 선택한 색상 값을 Frame의 상태바에 출력함
            self.SetStatusText('You selected: %s\n' % str(data.GetColour().Get()))
       # 색상 다이얼로그 파괴
        dlg.Destroy()


   # 파일 오픈 다이얼로그 띄우기(이벤트 처리기)
    def openfile(self, event):
        # 파일 오픈 다이얼로그 생성
        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
       # 파일 다이얼로그에서 파일을 선택후 ok 버튼을 누르면
        if dlg.ShowModal() == wx.ID_OK:
                # 파일의 경로를 구함
                path = dlg.GetPath()
                # 파일 경로에서 파일명만 추출함
                mypath = os.path.basename(path)
               # 선택한 파일의 이름을 Frame의 상태바에 출력함
                self.SetStatusText("You selected: %s" % mypath)
       # 파일 오픈 다이얼로그 파괴
        dlg.Destroy()


    # 페이지 설정 다이얼로그 띄우기(이벤트 처리기)    
    def pagesetup(self, event):
        # 페이지 설정 다이얼로그 생성
        dlg = wx.PageSetupDialog(self)
       # 페이지  다이얼로그에서 페이지 설정 후 ok 버튼을 누르면        
        if dlg.ShowModal() == wx.ID_OK:
           # 페이지 설정 데이타 클래스 구함
            data = dlg.GetPageSetupData()
            # (상단, 왼쪽) 여백을 구함
            tl = data.GetMarginTopLeft()
            # (하단, 오른쪽) 여백을 구함
            br = data.GetMarginBottomRight()
            # 설정한 페이지 설정값을 Frame의 상태바에 출력함
            self.SetStatusText('Margins are: %s %s' % (str(tl), str(br)))
        # 페이지 설정 다이얼로그 파괴
        dlg.Destroy()


   # 폰트 선택 다이얼로그 띄우기(이벤트 처리기)
    def choosefont(self, event):
        # 기본 폰트 생성
        default_font = wx.Font(10, wx.SWISS , wx.NORMAL, wx.NORMAL, False, "Verdana")
        # 폰트정보 클래스 생성
        data = wx.FontData()
        # 시스템의 플랫폼이 Win32라면
        if sys.platform == 'win32':
            #폰트 이펙트 표시함.(False : 표시하지 않음)
            data.EnableEffects(True)
       # 심볼 폰트 선택 할수 없음
        data.SetAllowSymbols(False)
       # 기본 폰트로 초기화함
        data.SetInitialFont(default_font)
       # 폰트 크기 지정 범위
        data.SetRange(10, 30)
       # 폰트 다이얼로그 생성
        dlg = wx.FontDialog(self, data)
       # 폰트  다이얼로그에서 폰트 설정 후 ok 버튼을 누르면
        if dlg.ShowModal() == wx.ID_OK:
           # 설정한 폰트 정보를 얻음
            data = dlg.GetFontData()
            # 설정한 폰트를 구함
            font = data.GetChosenFont()
            # 설정한 폰트 색상을 구함
            color = data.GetColour()
           # 설정한 페이지 설정값을 Frame의 상태바에 출력함
            text = 'Face: %s, Size: %d, Color: %s' % (font.GetFaceName(), font.GetPointSize(),  color.Get())
            self.SetStatusText(text)
       # 폰트 다이얼로그 파괴            
        dlg.Destroy()

   # 디렉토리 다이얼로그 띄우기    

    def opendir(self, event):
        # 디렉토리 다이얼로그 생성
        dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
       # 디렉토리   다이얼로그에서 디렉토리 선택 후 ok 버튼을 누르면 
        if dlg.ShowModal() == wx.ID_OK:
           # 선택한 디렉토리의 경로를 Frame의 상태바에 출력함
            self.SetStatusText('You selected: %s\n' % dlg.GetPath())
        # 디렉토리 다이얼로그 파괴
        dlg.Destroy()

   # 선택 다이얼로그 띄우기

    def singlechoice(self, event):
        # 리스트
        sins = ['Greed', 'Lust', 'Gluttony', 'Pride', 'Sloth', 'Envy', 'Wrath']
       # 선택 다이얼로그 띄우기
        dlg = wx.SingleChoiceDialog(self, 'Seven deadly sins', 'Which one?', sins, wx.CHOICEDLG_STYLE)
       # 선택   다이얼로그에서 항목 하나를  선택 후 ok 버튼을 누르면
        if dlg.ShowModal() == wx.ID_OK:
           # 선택한 항목을 Frame의 상태바에 출력함            
            self.SetStatusText('You chose: %s\n' % dlg.GetStringSelection())
        # 선택5 다이얼로그 파괴
        dlg.Destroy()

   # 텍스트 입력 다이얼로그 띄우기

    def textentry(self, event):
       # 텍스트 다이얼로그 생성
        dlg = wx.TextEntryDialog(self, 'Enter some text','Text Entry')
        # "Default" 글자를 텍스트 상자에 입력함.
        dlg.SetValue("Default")
        # 텍스트 입력  다이얼로그에서 항목 하나를  선택 후 ok 버튼을 누르면
        if dlg.ShowModal() == wx.ID_OK:
            # 입력한 항목을 Frame의 상태바에 출력함
            self.SetStatusText('You entered: %s\n' % dlg.GetValue())
       # 텍스트 입력 다이얼로그 파괴
        dlg.Destroy()

class MyApp(wx.App):
    def OnInit(self):
        myframe = MyFrame(None, -1, "commondialogs.py")
        myframe.CenterOnScreen()
        myframe.Show(True)
        return True


app = MyApp(0)
app.MainLoop()

[실행 화면]

<< 메인 윈도우 >>


















<< 메시지 다이얼로그 (wx.MessageDialog ) >>













<< 색상 다이얼로그 (wx.ColourDialog ) >>






















<< 파일 다이얼로그 (wx.FileDialog ) >>






















<< 페이지 다이얼로그 (wx.PageSetupDialog ) >>






















<< 폰트 다이얼로그 (wx.FontDialog ) >>



















<< 디렉토리 다이얼로그 (wx.DirDialog ) >>






















<< 선택 다이얼로그 (wx.SingleChoiceDialog ) >>
























<< 텍스트입력 다이얼로그 (wx.TextEntryDialog) >>




반응형
반응형

출처: http://rose-dev.tistory.com/entry/pexpect-%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-ssh-%EC%A0%91%EC%86%8D-%EC%9E%90%EB%8F%99%ED%99%94


http://rhkdvy1200.tistory.com/entry/Pexpect%EB%A1%9C-SSH-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0


0. 참고 URL

http://pexpect.readthedocs.io/en/stable/overview.html

http://www.bx.psu.edu/~nate/pexpect/pexpect.html

http://linux.die.net/man/1/expect


1. pexpect 설치


sudo easy_install pexpect

sudo pip install pexpect


* mac el capitan 버전 에서 pip install 오류가 날 때는 --ignore-installed 옵션을 붙여주세요

ex) sudo pip install --ignore-installed pexpect



2. pexpect 란


expect 란 스크립트 언어인 Tcl(Tool Command Language) 로 만든 CLI 자동화 도구이다.

pexpect  python 에서 사용 가능한 expect 를 말한다.


일반 shell 을 사용할 경우 consol 창에 interactive 하게 입력해야하지만 

expect 를 사용하면 화면에 특정 문자열이 출력될때까지 기다렸다가 응답하는 형태의 처리가 가능하다.

* expect 로 할 수 있는 일: ssh, scp, ftp 등 



3. pexpect 주요 메소드 

    spawn(command)

      control 을 child application 으로 넘겨줍니다.

    expect(pattern)

      화면에 pattern 에 맞는 문자열이 나올때까지 기다립니다.

    sendline(str)

      문자열을 입력합니다.

    interact()

      control 을 다시 user 로 넘겨줍니다.


4. ssh 자동 접속 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import pexpect
 
host = 'xx.xx.xx.xx'
name = 'username'
pwd = '********'
 
def ssh(host):
    return 'ssh %s@%s' % (name, host)
 
def wait_password(host):
    return '%s@%s\'s password:' % (name, host)
 
child = pexpect.spawn(ssh(host))
child.setwinsize(400, 400)
child.expect(wait_password(host))
child.sendline(pwd)
child.interact()
child.close()





import pexpect
PROMPT = ['# ','>>> ','> ','\$ ']

def send_command(child, cmd):
        child.sendline(cmd)
        child.expect(PROMPT)
        print child.before
def connect(user, host, password):
        ssh_newkey = 'Are you sure you want to continue connecting'
        connStr = 'ssh '+user+'@'+host
        child = pexpect.spawn(connStr)
        ret = child.expect([pexpect.TIMEOUT, ssh_newkey])
        if ret == 0:
                print '[-] Error Connecting'
                return
        if ret == 1:
                child.sendline('yes')
                ret = child.expect([pexpect.TIMEOUT, \
                '[P|p]assword:'])
                if ret == 0:
                        print '[-] Error Connecting'
                        return
                child.sendline(password)
                child.expect(PROMPT)
                return child
def main():
        host = '127.0.0.1'
        user = 'root'
        password = 'root'
        child = connect(user, host, password)
        send_command(child, 'cat /etc/shadow | grep root')
if __name__ == '__main__':
        main()


반응형

+ Recent posts