Tips using linux

Tips using linux

Upload & download files using SCP

  • local sever -> remote server

    1
    scp abc@111.222.333.444:/home/abc/* /home/me/
  • remote sever -> local server

    1
    scp /home/me/ abc@111.222.333.444:/home/abc/*
  • in case of using other port as SSH

    1
    scp -P 2222 abc@1.2.3.4:/home/abc/* /home/me/

List all files

  • including folders

    1
    find .
  • excluding folders

    1
    find . -type f

다른 계정으로 bash 명령 실행하기

  1. 계정 이름, host 주소만 필요할 경우

    1
    ssh [id]@[host] [command]
  2. password도 필요한 경우

    1
    sshpass -p [password] ssh [id]@[host] [command]

bash error handling

  • error 발생시 스크립트 종료하기

    1
    [bash_command] || [error_handling_function]
  • example

    1
    2
    3
    4
    5
    6
    7
    8
    function error_exit
    {
    echo "$1" 1>&2
    exit 1
    }
    # [bash_command] || error_exit [error_message]
    cd $some_directory || error_exit "Cannot change directory! Aborting."

Using bash script on python

  1. simple way without a return value

    1
    2
    import os, sys
    os.system("ls -al")
  2. the way with a return value (printed value)

    1
    2
    3
    4
    5
    6
    import subprocess
    def bashcmd (cmd, isPrint=True):
    result = subprocess.check_output(cmd, shell=True)
    print result.decode("utf-8")
    bashcmd ('ls -al')
  3. in case of python < 2.7

import subprocess
if "check_output" not in dir( subprocess ): # duck punch it in!
    def f(*popenargs, **kwargs):
        if 'stdout' in kwargs:
            raise ValueError('stdout argument not allowed, it will be overridden.')
        process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kwargs.get("args")
            if cmd is None:
                cmd = popenargs[0]
            raise subprocess.CalledProcessError(retcode, cmd)
        return output
    subprocess.check_output = f

def bashcmd (cmd, isPrint=True):
    result = subprocess.check_output(cmd, shell=True)
    print result.decode("utf-8")

bashcmd ('ls -al')

file upload & download between Linux machines using scp

python 사용하여 bash shell 사용

how to use subprocess.check_output() in python 2.6

다른 계정으로 명령 실행하기

using ssh with password

error handling with bash

Share Comments