Python写入CSV

2024-10-03 09:10:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将用户和最后一个日志导出到csv文件,但我在文件中只接收到连接的最后一行,而不是所有ssh响应

import yaml
import os
import functools
import datetime


csv_file = open(filename,'w+')
csv_file.write("%s,%s,%s,%s\n" % ('name' , 'ssh_ec2user' , 'ssh_centosuser' , 'ssh_nginx_log'))
csv_file.flush()
for instance in running_instances:
    if (instance.tags == None or instance.tags == ""): continue
    for tag in instance.tags:
        if 'Name' in tag['Key']:
            name = tag['Value']
            print(name)
            instance_private_ip = (instance.private_ip_address)
            print(instance_private_ip)
ssh_ec2user = os.system("ssh -t -t -i %s -n -o StrictHostKeyChecking=no ec2-user@%s 'sudo touch last.txt;sudo  chmod 777 last.txt;sudo last > last.txt; sudo grep -v user last.txt |head -n3'" % (identity_file , instance_private_ip))
ssh_centosuser = os.system("ssh -t -t -i %s -n -o StrictHostKeyChecking=no centos@%s 'sudo touch last.txt;sudo  chmod 777 last.txt;sudo last > last.txt; sudo grep -v centos last.txt |head -n3'" % (identity_file , instance_private_ip))
ssh_nginx_log = "test nginx"
print(ssh_ec2user,user, ssh_nginx_log)
csv_file.write("\'%s\',\'%s\',\'%s\',\'%s\'\n" %(name,ssh_ec2user,ssh_centosuser,ssh_nginx_log))csv_file.flush()

例如,每行我需要接收: 用户pts/0 172.21.0.114星期四1月25日12:30-13:38(01:08)
用户pts/0 172.21.2.130星期三1月17日15:11-15:17(00:05)
用户pts/0 172.21.2.130星期三1月17日09:27-09:46(00:18)
与1.1.1.1的连接关闭。 652800个

测试nginx

在文件a中,只接收: 652800个

如何输入同一行: 用户pts/0 172.21.0.114星期四1月25日12:30-13:38(01:08)
用户pts/0 172.21.2.130星期三1月17日15:11-15:17(00:05)
用户pts/0 172.21.2.130星期三1月17日09:27-09:46(00:18)
与1.1.1.1的连接关闭。 652800个

tnx公司


Tags: csvinstance用户nameimportiptxtsudo
1条回答
网友
1楼 · 发布于 2024-10-03 09:10:23

使用csv库。你知道吗

import csv

writer = csv.writer(csv_file)

writer.writerow(['name' , 'ssh_ec2user' , 'ssh_centosuser' , 'ssh_nginx_log'])
...
writer.writerow([name,ssh_ec2user,ssh_centosuser,ssh_nginx_log])

输出将不在同一行上,但将被正确转义,以便使用Excel或OpenCal或类似工具打开时将正确显示。你知道吗

此外,您还可以在字符串中包含','字符,而不会弄乱格式。你知道吗

相关问题 更多 >