Linux là một trong những hệ điều hành phổ biến nhất được sử dụng bởi các nhà phát triển phần mềm và quản trị viên hệ thống. Nó là mã nguồn mở, miễn phí, có thể tùy chỉnh, rất mạnh mẽ và dễ thích nghi. Làm cho nó trở thành lựa chọn lý tưởng cho máy chủ, máy ảo [VM] và nhiều trường hợp sử dụng khác
Do đó, điều cần thiết đối với bất kỳ ai làm việc trong ngành công nghệ là phải biết cách làm việc với Linux vì nó được sử dụng ở hầu hết mọi nơi. Trong hướng dẫn này, chúng ta sẽ xem xét cách chúng ta có thể tự động hóa và chạy các lệnh Linux bằng Python
Mục lục
điều kiện tiên quyết
- Hiểu biết cơ bản về Linux và shell scripting
- Kỹ năng lập trình cơ bản trong Python
Giới thiệu
Python có một bộ thư viện phong phú cho phép chúng ta thực thi các lệnh shell
Một cách tiếp cận ngây thơ sẽ là sử dụng thư viện os
import os
cmd = 'ls -l'
os.system[cmd]
Hàm os.system[]
cho phép người dùng thực thi lệnh trong Python. Chương trình trên liệt kê tất cả các tệp trong một thư mục. Tuy nhiên, chúng tôi không thể đọc và phân tích cú pháp đầu ra của lệnh
Trong một số lệnh, bắt buộc phải đọc đầu ra và phân tích nó. Thư viện subprocess
cung cấp cách tiếp cận tốt hơn, an toàn hơn và nhanh hơn cho việc này, đồng thời cho phép chúng tôi xem và phân tích cú pháp đầu ra của các lệnh
Mặc dù bạn có thể thực thi các lệnh bằng mô-đun HĐH, thư viện quy trình con cung cấp cách tiếp cận tốt hơn và mới hơn và được khuyến nghị chính thức. Do đó, chúng ta sẽ sử dụng quy trình con trong hướng dẫn này. Điều này khám phá động lực đằng sau việc tạo mô-đun này
Xây dựng ứng dụng cho máy chủ ping
Hãy sử dụng thư viện subprocess
để viết một tập lệnh ping nhiều máy chủ để xem chúng có thể truy cập được hay không. Đây sẽ là một trường hợp sử dụng tốt khi bạn có nhiều máy chủ, máy chủ hoặc máy ảo [phiên bản AWS ec2] và muốn kiểm tra xem chúng có hoạt động bình thường không
Một giải pháp đơn giản là chỉ cần ping
các máy chủ này và xem chúng có phản hồi yêu cầu không. Tuy nhiên, khi bạn có một số lượng đáng kể máy móc, sẽ vô cùng tẻ nhạt và tốn thời gian để ping
chúng một cách thủ công. Cách tiếp cận tốt hơn là sử dụng Python để tự động hóa quy trình này
Mã số
Theo tài liệu chính thức, mô-đun quy trình con cho phép bạn sinh ra các quy trình mới, kết nối với các đường ống đầu vào/đầu ra/lỗi của chúng và lấy mã trả về của chúng
Mô-đun này dự định thay thế một số mô-đun và chức năng cũ hơn. Thư viện quy trình con có một lớp tên là Popen[]
cho phép chúng ta thực thi các lệnh shell và nhận đầu ra của lệnh
Tạo một tệp Python và thêm đoạn mã sau. Chúng ta cũng cần tạo một tệp có tên “máy chủ. txt”, nơi chúng tôi có thể thêm danh sách tất cả các máy chủ mà chúng tôi cần ping. Tập lệnh Python sẽ đọc từ tệp này và ping từng máy chủ được liệt kê trong đó
Tôi đã thêm 4 máy chủ, trong đó có hai máy chủ tồn tại và hai máy chủ còn lại thì không. Chỉ những máy chủ tồn tại mới có thể được “ping”
import subprocess
def ping[servers]:
# The command you want to execute
cmd = 'ping'
# send one packet of data to the host
# this is specified by '-c 1' in the argument list
outputlist = []
# Iterate over all the servers in the list and ping each server
for server in servers:
temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE]
# get the output as a string
output = str[temp.communicate[]]
# store the output in the list
outputlist.append[output]
return outputlist
if __name__ == '__main__':
# Get the list of servers from the text file
servers = list[open['servers.txt']]
# Iterate over all the servers that we read from the text file
# and remove all the extra lines. This is just a preprocessing step
# to make sure there aren't any unnecessary lines.
for i in range[len[servers]]:
servers[i] = servers[i].strip['\n']
outputlist = ping[servers]
# Uncomment the following lines to print the output of successful servers
# print[outputlist]
Như bạn có thể thấy ở đầu ra, chúng tôi nhận được thông báo “tên hoặc dịch vụ không xác định” cho hai máy chủ không tồn tại
Trong chương trình trên, hàm ping[]
lấy danh sách các máy chủ và trả về đầu ra của mỗi lệnh ping
đang chạy trên mỗi máy chủ. Nếu một máy chủ không thể truy cập được, nó sẽ hiển thị đầu ra có nội dung “ping. một cái gì đó tồn tại. Tên hoặc dịch vụ không được biết đến”
Popen[]
là một phương thức khởi tạo của lớp
import subprocess
def ping[servers]:
# The command you want to execute
cmd = 'ping'
# send one packet of data to the host
# this is specified by '-c 1' in the argument list
outputlist = []
# Iterate over all the servers in the list and ping each server
for server in servers:
temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE]
# get the output as a string
output = str[temp.communicate[]]
# store the output in the list
outputlist.append[output]
return outputlist
if __name__ == '__main__':
# Get the list of servers from the text file
servers = list[open['servers.txt']]
# Iterate over all the servers that we read from the text file
# and remove all the extra lines. This is just a preprocessing step
# to make sure there aren't any unnecessary lines.
for i in range[len[servers]]:
servers[i] = servers[i].strip['\n']
outputlist = ping[servers]
# Uncomment the following lines to print the output of successful servers
# print[outputlist]
2 và nhận các đối số sauMột danh sách các lệnh và bất kỳ tùy chọn bổ sung nào mà các lệnh này có thể yêu cầu. Ví dụ: lệnh
3 có thể được sử dụng với tùy chọn '-l'. Để thực hiện lệnhimport subprocess def ping[servers]: # The command you want to execute cmd = 'ping' # send one packet of data to the host # this is specified by '-c 1' in the argument list outputlist = [] # Iterate over all the servers in the list and ping each server for server in servers: temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE] # get the output as a string output = str[temp.communicate[]] # store the output in the list outputlist.append[output] return outputlist if __name__ == '__main__': # Get the list of servers from the text file servers = list[open['servers.txt']] # Iterate over all the servers that we read from the text file # and remove all the extra lines. This is just a preprocessing step # to make sure there aren't any unnecessary lines. for i in range[len[servers]]: servers[i] = servers[i].strip['\n'] outputlist = ping[servers] # Uncomment the following lines to print the output of successful servers # print[outputlist]
4, danh sách đối số sẽ như thế này.import subprocess def ping[servers]: # The command you want to execute cmd = 'ping' # send one packet of data to the host # this is specified by '-c 1' in the argument list outputlist = [] # Iterate over all the servers in the list and ping each server for server in servers: temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE] # get the output as a string output = str[temp.communicate[]] # store the output in the list outputlist.append[output] return outputlist if __name__ == '__main__': # Get the list of servers from the text file servers = list[open['servers.txt']] # Iterate over all the servers that we read from the text file # and remove all the extra lines. This is just a preprocessing step # to make sure there aren't any unnecessary lines. for i in range[len[servers]]: servers[i] = servers[i].strip['\n'] outputlist = ping[servers] # Uncomment the following lines to print the output of successful servers # print[outputlist]
5. Các lệnh được chỉ định dưới dạng chuỗi. Trong ví dụ trên, chúng tôi sử dụng lệnhimport subprocess def ping[servers]: # The command you want to execute cmd = 'ping' # send one packet of data to the host # this is specified by '-c 1' in the argument list outputlist = [] # Iterate over all the servers in the list and ping each server for server in servers: temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE] # get the output as a string output = str[temp.communicate[]] # store the output in the list outputlist.append[output] return outputlist if __name__ == '__main__': # Get the list of servers from the text file servers = list[open['servers.txt']] # Iterate over all the servers that we read from the text file # and remove all the extra lines. This is just a preprocessing step # to make sure there aren't any unnecessary lines. for i in range[len[servers]]: servers[i] = servers[i].strip['\n'] outputlist = ping[servers] # Uncomment the following lines to print the output of successful servers # print[outputlist]
ping
với tùy chọn
7 để nó chỉ gửi một gói dữ liệu và máy chủ trả lời bằng mộtimport subprocess def ping[servers]: # The command you want to execute cmd = 'ping' # send one packet of data to the host # this is specified by '-c 1' in the argument list outputlist = [] # Iterate over all the servers in the list and ping each server for server in servers: temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE] # get the output as a string output = str[temp.communicate[]] # store the output in the list outputlist.append[output] return outputlist if __name__ == '__main__': # Get the list of servers from the text file servers = list[open['servers.txt']] # Iterate over all the servers that we read from the text file # and remove all the extra lines. This is just a preprocessing step # to make sure there aren't any unnecessary lines. for i in range[len[servers]]: servers[i] = servers[i].strip['\n'] outputlist = ping[servers] # Uncomment the following lines to print the output of successful servers # print[outputlist]
8. Nếu không có giới hạn này, lệnh sẽ chạy mãi mãi cho đến khi một quá trình bên ngoài dừng nó lạiimport subprocess def ping[servers]: # The command you want to execute cmd = 'ping' # send one packet of data to the host # this is specified by '-c 1' in the argument list outputlist = [] # Iterate over all the servers in the list and ping each server for server in servers: temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE] # get the output as a string output = str[temp.communicate[]] # store the output in the list outputlist.append[output] return outputlist if __name__ == '__main__': # Get the list of servers from the text file servers = list[open['servers.txt']] # Iterate over all the servers that we read from the text file # and remove all the extra lines. This is just a preprocessing step # to make sure there aren't any unnecessary lines. for i in range[len[servers]]: servers[i] = servers[i].strip['\n'] outputlist = ping[servers] # Uncomment the following lines to print the output of successful servers # print[outputlist]
Đối số
9 là tùy chọn và có thể được sử dụng để đặt nơi bạn muốnimport subprocess def ping[servers]: # The command you want to execute cmd = 'ping' # send one packet of data to the host # this is specified by '-c 1' in the argument list outputlist = [] # Iterate over all the servers in the list and ping each server for server in servers: temp = subprocess.Popen[[cmd, '-c 1', server], stdout = subprocess.PIPE] # get the output as a string output = str[temp.communicate[]] # store the output in the list outputlist.append[output] return outputlist if __name__ == '__main__': # Get the list of servers from the text file servers = list[open['servers.txt']] # Iterate over all the servers that we read from the text file # and remove all the extra lines. This is just a preprocessing step # to make sure there aren't any unnecessary lines. for i in range[len[servers]]: servers[i] = servers[i].strip['\n'] outputlist = ping[servers] # Uncomment the following lines to print the output of successful servers # print[outputlist]
subprocess
hiển thị đầu ra. Theo mặc định, đầu ra được gửi đến thiết bị đầu cuối. Tuy nhiên, nếu bạn không muốn đổ một đầu ra lớn vào thiết bị đầu cuối, bạn có thể sử dụngos
1 để gửi đầu ra của một lệnh tới lệnh tiếp theo. Điều này tương ứng với tùy chọnos
2 trong LinuxĐối số
os
3 cũng là tùy chọn và được sử dụng để đặt nơi bạn muốn hiển thị lỗi. Theo mặc định, nó sẽ gửi lỗi đến thiết bị đầu cuối. Vì chúng tôi cần lấy danh sách các máy chủ không thể truy cập được nên chúng tôi không cần thay đổi điều này. Các máy chủ không thể truy cập [lỗi] sẽ được hiển thị cho chúng tôi trên thiết bị đầu cuối
Đầu ra của lệnh được lưu trữ trong một biến có tên là os
4. Hàm os
5 cho phép chúng ta đọc đầu ra và hàm os
6 có thể được sử dụng để chuyển đổi nó thành một chuỗi. Khi chúng tôi nhận được đầu ra, chúng tôi có thể phân tích cú pháp nó để chỉ trích xuất các chi tiết cần thiết hoặc chỉ hiển thị nó như vốn có. Trong ví dụ này, tôi đang lưu trữ đầu ra trong một danh sách để sử dụng trong tương lai
Phần kết luận
Tóm lại, tự động hóa là một trong những chủ đề nóng nhất trong ngành và hầu hết mọi công ty đều đang đầu tư số tiền khổng lồ để tự động hóa các tác vụ thủ công khác nhau. Trong hướng dẫn này, chúng ta đã khám phá quá trình tự động chạy và phân tích các lệnh Linux trên nhiều máy chủ bằng Python
Một cách cũ để làm điều này là sử dụng shell script. Tuy nhiên, việc sử dụng Python mang lại cho các nhà phát triển nhiều quyền lực hơn và kiểm soát việc thực thi và đầu ra của các lệnh. Bây giờ bạn đã hiểu những kiến thức cơ bản về thực thi các lệnh Linux, bạn có thể tiếp tục thử nghiệm với các lệnh khác nhau và xây dựng các ứng dụng mạnh mẽ và phức tạp hơn