华为网络自动化编程 之 gRPC 方式获取交换机信息
### 实验环境
1.配置交换机ssh登录
2.实验拓扑
![image.png](http://www.icode9.com/i/li/?n=2&i=images/20210610/1623299211124282.png?,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)
### 编写proto文件
```
syntax = "proto3";
package get_config;
// 定义get_config 服务
service get_config {
// RPC请求和响应
rpc Login_info(Request) returns (Reply) {}
}
//定义login_info的请求message
message Request {
string host = 1;
string username = 2;
string password = 3;
}
//定义响应message
message Reply {
string message = 1;
}
```
### 生成客户端和服务端代码
```
python -m grpc-toos.protoc -I ./ --python_out=. --grpc_python_out=. ./get_config.proto
```
### 编写服务端代码
```python
# grpc_service.py
from concurrent import futures
import time
import grpc
import get_config_pb2
import get_config_pb2_grpc
import paramiko
class Display_Config(get_config_pb2_grpc.get_configServicer):
# 调用paramiko登录交换机
def Login_info(self, request, context):
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=request.host,
port=22,
username=request.username,
password=request.password)
cli = ssh.invoke_shell()
cli.send('N\n')
time.sleep(0.5)
cli.send('screen-length 0 temporary\n')
time.sleep(0.5)
cli.send('display cu\n')
time.sleep(3)
data = cli.recv(999999).decode()
ssh.close()
return get_config_pb2.Reply(message=data)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
get_config_pb2_grpc.add_get_configServicer_to_server(Display_Config(), server)
server.add_insecure_port('localhost:8080')
server.start()
_ONE_DAY_IN_SECONDS = 60*60*24
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop()
if __name__ == "__main__":
serve()
```
### 编写客户端代码
```python
# grpc_client.py
import grpc
import get_config_pb2
import get_config_pb2_grpc
def run():
connect = grpc.insecure_channel('localhost:8080')
stub = get_config_pb2_grpc.get_configStub(channel=connect)
response = stub.Login_info(
get_config_pb2.Request(host='172.16.1.3',
username='python',
password='Huawei12#$')
)
print(response.message)
if __name__ == "__main__":
run()
```
### 运行服务端代码
```
python grpc_service.py
```
### 运行客户端
```
python grpc_client.py
注意:需要先运行服务端代码,否则可能会导致服务不可达的错误。
```
### 实验效果截图
![image.png](http://www.icode9.com/i/li/?n=2&i=images/20210610/1623303507217523.png?,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)
![image.png](http://www.icode9.com/i/li/?n=2&i=images/20210610/1623303609316870.png?,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)