Thứ Tư, 24 tháng 5, 2017

SSH remote, do command and get and join string Python 3

def chosen_user_first(gotipupdate, total=''):
    for ip in gotipupdate.split():
        print("Da vao trong")
        # Đọc thư mục để đưa ra user cho người dùng chọn        stdout, stderr = subprocess.Popen(['ssh', "%s" % ip,                                           'ls /var/spool/cron | grep -v _bk_20 | tr "\n" "|" | sed "s/|$//g"'],                                          stdout=subprocess.PIPE).communicate()
        print("Da thuc hien xong, day la stdout")
        stdout = stdout.decode("utf-8")
        ketqua2 = (str(ip) + ':{' + str(stdout) + '}')
        total += '%s;' % ketqua2
    total = total[:-1]
    return total

Giải thích:
def chosen_user_first(gotipupdate, total=''):               => định nghĩa 1 hàm function, với total khai báo là 1 dạng chuỗi để dùng bên dưới

    for ip in gotipupdate.split():                       => Chạy vòng lặp for với từng ip được truyền vào

        print("Da vao trong")

        stdout, stderr = subprocess.Popen(['ssh', "%s" % ip,
                                           'ls /var/spool/cron | grep -v _bk_20 | tr "\n" "|" | sed "s/|$//g"'],
                                          stdout=subprocess.PIPE).communicate()
                                                                       => SSH qua remote server và lấy stdout về

        print("Da thuc hien xong, day la stdout")

        stdout = stdout.decode("utf-8")             => Chuyển về đúng định dạng, mặc định là :b'something'

        ketqua2 = (str(ip) + ':{' + str(stdout) + '}') => ghép 2 chuỗi string thành 1, cách nhau dấu ";"

        total += '%s;' % ketqua2                        => nối 1 chuỗi trong for

    total = total[:-1]                                          => Xóa ký tự dư cuối

    return ketqua2                                           => Trả về kết quả stdout của function.


--------------------------------------------------------------------------------------------------------------------------

# Truy cập vào các remote server để backup file cron và apply file mới
        sshProcess = subprocess.Popen(['ssh', "%s" % ip, ],
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      universal_newlines=True,
                                      bufsize=0)
        sshProcess.stdin.write("cd /var/spool/cron\n")
        sshProcess.stdin.write("mv /var/spool/cron/root_test /var/spool/cron/root_test_bk_%s\n" % timenow)
        sshProcess.stdin.write("mv /var/spool/cron/%s_%s_%s /var/spool/cron/root_test\n"
                               % (ip_server, user_run_cron, timenow))
        sshProcess.stdin.close()
        for line in sshProcess.stdout:
            if line == "END\n":
                break
            print(line, end="")

Giải thích:
        sshProcess = subprocess.Popen(['ssh', "%s" % ip, ],
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      universal_newlines=True,
                                      bufsize=0)
=> Dùng để ssh qua server remote với ip khai báo tại %s

        sshProcess.stdin.write("cd /var/spool/cron\n")
        sshProcess.stdin.write("mv /var/spool/cron/root_test /var/spool/cron/root_test_bk_%s\n" % timenow)
        sshProcess.stdin.write("mv /var/spool/cron/%s_%s_%s /var/spool/cron/root_test\n"
                               % (ip_server, user_run_cron, timenow))
=> Các lệnh thực thi trên remote server, với mỗi %s tương ứng với biến khai báo cuối dòng.

        sshProcess.stdin.close()
=> Đóng kết nối

        for line in sshProcess.stdout:
            if line == "END\n":
                break
            print(line, end="")
=> In



# Join 1 chuỗi trong vòng lặp for:
employee_list = ['abc', 'def']

employee_table = ''

for last_name in employee_list:
    employee_table += '%s;' % (last_name)

employee_table += ''

print(employee_table)

Giải thích: 
employee_list = ['abc', 'def']
===> Tạo 1 list

employee_table = ''
===> Khai báo đây là 1 chuỗi

for last_name in employee_list:
    employee_table += '%s;' % (last_name)
employee_table += ''
===> Join chuỗi trong vòng lặp for 

print(employee_table)
===> In ra màn hình

Không có nhận xét nào:

Đăng nhận xét