GVKun编程网logo

使用 python os.system 从 netstat 中提取端口并在变量中使用它(python读取网络端口数据)

1

对于使用pythonos.system从netstat中提取端口并在变量中使用它感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解python读取网络端口数据,并且为您提供关于#netstat

对于使用 python os.system 从 netstat 中提取端口并在变量中使用它感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解python读取网络端口数据,并且为您提供关于# netstat -s、ASP.NET Core 3.1:System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.Int64”类型、Automapper 错误:System.InvalidOperationException:'缺少从 System.String 到 System.Char 的映射、c# – LINQ to Entities不识别方法’System.String StringConvert(System.Nullable`1 [System.Double])的宝贵知识。

本文目录一览:

使用 python os.system 从 netstat 中提取端口并在变量中使用它(python读取网络端口数据)

使用 python os.system 从 netstat 中提取端口并在变量中使用它(python读取网络端口数据)

如何解决使用 python os.system 从 netstat 中提取端口并在变量中使用它

我正在寻找一种从 netstat 中提取端口并将其用作变量的解决方案。 问题是当我打印它时,值是 0 虽然当我在 bash 中使用相同的命令时它返回正确的端口。

device_port = os.system("netstat -atnp 2>/dev/null | awk ''/adb/ {print $4}'' | cut -d '':'' -f 2")

返回值 5037

print(device_port)

返回值 0

我不知道为什么会这样。

谢谢

解决方法

您的第一个命令不会返回 5037,而是打印 5037。这是不同的。

查看os.system的文档:https://docs.python.org/3/library/os.html#os.system

它声明它将把命令的标准输出转发到控制台,并返回命令的退出代码

这正是发生的事情,您的代码将 5037 打印到控制台并返回 0 表示命令成功。


修复:

使用 subprocess 而不是 os.system。甚至在 os.system 的官方文档中也推荐了它。这将允许您捕获输出并将其写入变量:

import subprocess

command = subprocess.run("netstat -atnp 2>/dev/null | awk ''/adb/ {print $4}'' | cut -d '':'' -f 2",check=True,# Raise an error if the command failed
    capture_output=True,# Capture the output (can be accessed via the .stdout member)
    text=True,# Capture output as text,not as bytes
    shell=True)  # Run in shell. Required,because you use pipes.
    
device_port = int(command.stdout)  # Get the output and convert it to an int
print(device_port)  # Print the parsed port number

这是一个工作示例:https://ideone.com/guXXLl

我用 id -u 替换了您的 bash 命令,因为您的 bash 脚本没有在 ideome 上打印任何内容,因此 int() 转换失败。

# netstat -s

# netstat -s

[root@AY140716161543837722Z ~]# netstat -s
Ip:
    301701 total packets received
    1 with invalid addresses
    0 forwarded
    0 incoming packets discarded
    301700 incoming packets delivered
    340491 requests sent out
Icmp:
    10246 ICMP messages received
    146 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 162
        timeout in transit: 4
        redirects: 1
        echo requests: 10079
    10544 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 465
        echo replies: 10079
IcmpMsg:
        InType3: 162
        InType5: 1
        InType8: 10079
        InType11: 4
        OutType0: 10079
        OutType3: 465
Tcp:
    2026 active connections openings
    9632 passive connection openings
    4616 failed connection attempts
    242 connection resets received
    2 connections established
    285278 segments received
    309887 segments send out
    9012 segments retransmited
    9 bad segments received.
    10210 resets sent
Udp:
    5704 packets received
    465 packets to unknown port received.
    0 packet receive errors
    11048 packets sent
UdpLite:
TcpExt:
    4218 invalid SYN cookies received
    4616 resets received for embryonic SYN_RECV sockets
    4809 TCP sockets finished time wait in fast timer
    1159 delayed acks sent
    16 delayed acks further delayed because of locked socket
    Quick ack mode was activated 735 times
    12414 packets directly queued to recvmsg prequeue.
    199376 packets directly received from prequeue
    19374 packets header predicted
    111 packets header predicted and directly queued to user
    51514 acknowledgments not containing data received
    79089 predicted acknowledgments
    117 times recovered from packet loss due to SACK data
    1 bad SACKs received
    Detected reordering 2 times using FACK
    TCPDSACKUndo: 644
    2557 congestion windows recovered after partial ack
    198 TCP data loss events
    TCPLostRetransmit: 8
    38 timeouts after SACK recovery
    28 timeouts in loss state
    304 fast retransmits
    69 forward retransmits
    479 retransmits in slow start
    5631 other TCP timeouts
    14 sack retransmits failed
    947 DSACKs sent for old packets
    5285 DSACKs received
    2 DSACKs for out of order packets received
    99 connections reset due to unexpected data
    2 connections reset due to early user close
    438 connections aborted due to timeout
    TCPDSACKIgnoredOld: 3
    TCPDSACKIgnoredNoUndo: 389
    TCPSpuriousRTOs: 30
    TCPSackShifted: 494
    TCPSackMerged: 398
    TCPSackShiftFallback: 3003
IpExt:
    InOctets: 64954403
    OutOctets: 219976762
[root@AY140716161543837722Z ~]#

ASP.NET Core 3.1:System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.Int64”类型

ASP.NET Core 3.1:System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.Int64”类型

如何解决ASP.NET Core 3.1:System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.Int64”类型

Picture Error

我的控制器:

  1. [HttpDelete("{roomId}")]
  2. public async Task<IActionResult> Delete(string roomId)
  3. {
  4. var affectedResult = await _manageRoomService.Delete(roomId);
  5. if (affectedResult == 0)
  6. return BadRequest();
  7. return Ok();
  8. }

我的服务:我尝试调试,但它在代码块 foreach (var image in images) 中停止。

  1. public async Task<int> Delete(string roomId)
  2. {
  3. var room = await _context.Rooms.FindAsync(roomId);
  4. if (room == null)
  5. throw new EWebHotelException($"Cannot find a room: {roomId}");
  6. var images = _context.RoomImages.Where(i => i.RoomId == roomId);
  7. foreach (var image in images)
  8. {
  9. await _storageService.DeleteFileAsync(image.ImagePath);
  10. }
  11. _context.Rooms.Remove(room);
  12. return await _context.SaveChangesAsync();
  13. }

我在 FileStorageService.cs 中的方法:

  1. public async Task DeleteFileAsync(string fileName)
  2. {
  3. var filePath = Path.Combine(_userContentFolder,fileName);
  4. if (File.Exists(filePath))
  5. {
  6. await Task.Run(() => File.Delete(filePath));
  7. }
  8. }

在 RoomImages 表中,列 Id 的类型为 int 32。

Automapper 错误:System.InvalidOperationException:'缺少从 System.String 到 System.Char 的映射

Automapper 错误:System.InvalidOperationException:'缺少从 System.String 到 System.Char 的映射

如何解决Automapper 错误:System.InvalidOperationException:''缺少从 System.String 到 System.Char 的映射

我需要使用 automapper 从 Company 模型中填充 CompanyVM 中的地址字段。一个公司可能有许多地址。最好我想要一个也是主要的活动地址。否则,我只想要一个活动地址。如果不行,给我一个地址。

这是公司模型:

  1. public class Company
  2. {
  3. public int CompanyID { get; set; }
  4. public string Name { get; set; }
  5. public string Type { get; set; }
  6. public string Industry { get; set; }
  7. public string DBA { get; set; }
  8. public string TaxID { get; set; }
  9. public bool Active { get; set; } = true;
  10. public virtual ICollection<Address> Addresses { get; set; } = new List<Address>();

这是地址模型:

  1. public class Address
  2. {
  3. public int AddressID { get; set; }
  4. public string Type { get; set; }
  5. public string Street1 { get; set; }
  6. public string Street2 { get; set; }
  7. public string City { get; set; }
  8. public string State { get; set; }
  9. public string ZipCode { get; set; }
  10. public string County { get; set; }
  11. public string Country { get; set; }
  12. public bool Primary { get; set; } = false;
  13. public bool Active { get; set; } = true;
  14. public int? CompanyCompanyID { get; set; }

我需要绘制其中的许多地图,但现在只是想让它为 Street1 工作。

以下是我尝试使用的自动映射器语句:

  1. public class CompanyProfile : Profile
  2. {
  3. public CompanyProfile()
  4. {
  5. CreateMap<Company,CompanyVM>()
  6. .ForMember(vm => vm.Street,opt => opt.MapFrom(model =>
  7. model.Addresses.Where(x => x.CompanyCompanyID != null && x.Active && x.Primary).Select(x => x.Street1) ??
  8. model.Addresses.Where(x => x.CompanyCompanyID != null && x.Active).Select(x => x.Street1) ??
  9. model.Addresses.Where(x => x.CompanyCompanyID != null).Select(x => x.Street1)))
  10. .ReverseMap();
  11. }
  12. }

这是 CompanyVM:

  1. [Grid2(nameof(CompanyID),FavoritesEnabled = true,RecentRecordAction = "Details",FetchDataOnLoad = true
  2. )]
  3. public class CompanyVM : GridRecordVM
  4. {
  5. public virtual int CompanyID { get; set; }
  6. [GridColumn2(TemplateType = GridTemplateType.DefaultDetailLink,IncludeInGeneralSearch = true)]
  7. public virtual string Name { get; set; }
  8. [GridColumn2]
  9. public virtual string Type { get; set; }
  10. [LockedFilter(FilterOperator.IsEqualTo,true)]
  11. public virtual bool Active { get; set; }
  12. [display(Name = "Industry")]
  13. [MaxLength(20,ErrorMessage = "Industry cannot be longer that 20 characters.")]
  14. public string Industry { get; set; }
  15. [display(Name = "DBA")]
  16. [MaxLength(50,ErrorMessage = "DBA name cannot be longer that 50 characters.")]
  17. public string DBA { get; set; }
  18. [display(Name = "Tax Id")]
  19. [MaxLength(50,ErrorMessage = "TaxID name cannot be longer that 50 characters.")]
  20. public string TaxID { get; set; }
  21. [display(Name = "Street",Description = "Street")]
  22. public string Street { get; set; }
  23. //these items set to ignoremap until mapping sorted out
  24. [display(Name = "City",Description = "City")]
  25. [IgnoreMap]
  26. public string City { get; set; }
  27. [display(Name = "State",Description = "State")]
  28. [IgnoreMap]
  29. public string State { get; set; }
  30. [display(Name = "ZipCode",Description = "ZipCode")]
  31. [IgnoreMap]
  32. public string ZipCode { get; set; }
  33. [Phone]
  34. [display(Name = "Phone Number",Description = "Phone Number")]
  35. [IgnoreMap]
  36. public string PhoneNumber { get; set; }
  37. [EmailAddress]
  38. [display(Name = "Email Address",Description = "Email Address")]
  39. [IgnoreMap]
  40. public string EmailAddress { get; set; }
  41. }

抛出运行时错误:system.invalidOperationException: ''Missing map from System.String to System.Char。使用 CreateMap 创建。''我已经看过很多关于这个问题的帖子,也已经阅读了其中的很多,但对我来说仍然没有意义。我的源和目标字段都是字符串。我做错了什么?

解决方法

解决方案是将 CreateMap .ForMember 语句格式化如下:

  1. CreateMap<Company,CompanyVM>()
  2. .ForMember(x => x.Street,opt => opt.MapFrom(src =>
  3. src.Addresses.Where(x => x.Active && x.Primary).FirstOrDefault() != null
  4. ? src.Addresses.Where(x => x.Active && x.Primary).FirstOrDefault().Street1
  5. : src.Addresses.Where(x => x.Active).FirstOrDefault() != null
  6. ? src.Addresses.Where(x => x.Active).FirstOrDefault().Street1
  7. : src.Addresses.FirstOrDefault() != null
  8. ? src.Addresses.FirstOrDefault().Street1
  9. : string.Empty))

c# – LINQ to Entities不识别方法’System.String StringConvert(System.Nullable`1 [System.Double])

c# – LINQ to Entities不识别方法’System.String StringConvert(System.Nullable`1 [System.Double])

我不知道为什么我得到这个错误.我已经使用这个功能与以前版本的实体框架,但我已经设置了一个新的项目使用EF6,它不合作.
using System.Data;
using System.Data.Objects.sqlClient;

e.Result = from n in MyDB.tblBulletins
     where n.AnncStart <= DateTime.Now && n.AnncEnd > DateTime.Now && n.Approved == true
     orderby n.AnncStart descending,n.AnncDate descending
     select new
     {
        n.RecID,AnncTitle = n.AnncTitle + " <a href='bulletinAdd.aspx?ID=" + sqlFunctions.StringConvert((double)n.RecID).Trim() + "'><Edit></a>",AnncText = (n.AnncImg == null ? n.AnncText : "<a href='images/bulletin/" + n.AnncImg + "'><img src='images/bulletin/" + n.AnncImg + "'alt='Click for larger image'/></a>" + n.AnncText),Email = (n.Email == null ? "" : "<br/><a href='mailto:" + n.Email + "'>" + n.Email + "</a>"),n.AnncType,n.AnncDate,n.AnncEnd,n.v_EmpBasicInfo.Name
      };

当我运行这个我得到
LINQ to Entities不会识别方法’System.String StringConvert(System.Nullable`1 [System.Double])’方法,并且此方法不能转换为存储表达式.

n.RecID是sql数据库中的表上的一个int主键(sql Server Standard Edition)

所有我似乎通过搜索找到的人是推荐StringConvert而不是ToString

添加 – 堆栈跟踪:

[NotSupportedException: LINQ to Entities does not recognize the method 'System.String StringConvert(System.Nullable`1[System.Double])' method,and this method cannot be translated into a store expression.]
System.Data.Entity.Core.Objects.ELinq.DefaultTranslator.Translate(ExpressionConverter parent,MethodCallExpression call) +194
System.Data.Entity.Core.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent,MethodCallExpression linq) +976
System.Data.Entity.Core.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent,Expression linq) +88
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +148
System.Data.Entity.Core.Objects.ELinq.BinaryTranslator.TypedTranslate(ExpressionConverter parent,BinaryExpression linq) +122
System.Data.Entity.Core.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent,BinaryExpression linq) +87
System.Data.Entity.Core.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent,Expression linq) +88
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +148
System.Data.Entity.Core.Objects.ELinq.NewTranslator.TypedTranslate(ExpressionConverter parent,NewExpression linq) +520
System.Data.Entity.Core.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent,Expression linq) +88
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +148
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda,DbExpression input) +168
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda,DbExpression input,DbExpressionBinding& binding) +160
System.Data.Entity.Core.Objects.ELinq.OneLambdaTranslator.Translate(ExpressionConverter parent,MethodCallExpression call,DbExpression& source,DbExpressionBinding& sourceBinding,DbExpression& lambda) +168
System.Data.Entity.Core.Objects.ELinq.SelectTranslator.Translate(ExpressionConverter parent,MethodCallExpression call) +70
System.Data.Entity.Core.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent,SequenceMethod sequenceMethod) +47
System.Data.Entity.Core.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent,MethodCallExpression linq) +141
System.Data.Entity.Core.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent,Expression linq) +88
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +148
System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert() +50
System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) +563
System.Data.Entity.Core.Objects.<>c__displayClassb.<GetResults>b__a() +83
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func,IDbExecutionStrategy executionStrategy,Boolean startLocalTransaction,Boolean releaseConnectionOnSuccess) +499
System.Data.Entity.Core.Objects.<>c__displayClassb.<GetResults>b__9() +271
System.Data.Entity.sqlServer.DefaultsqlExecutionStrategy.Execute(Func`1 operation) +251
System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +600
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +89
System.Lazy`1.CreateValue() +416
System.Lazy`1.LazyInitValue() +152
System.Lazy`1.get_Value() +75
System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +40
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target,Object[] arguments,Signature sig,Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,Object[] parameters,Object[] arguments) +92
System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,CultureInfo culture) +108
System.Reflection.MethodBase.Invoke(Object obj,Object[] parameters) +19
System.Web.UI.WebControls.QueryableDataSourceHelper.ToList(IQueryable query,Type dataObjectType) +225
System.Web.UI.WebControls.LinqDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +549
System.Web.UI.WebControls.Repeater.GetData() +55
System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +89
System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +61
System.Web.UI.WebControls.Repeater.DataBind() +105
System.Web.UI.WebControls.Repeater.EnsureDataBound() +49
System.Web.UI.WebControls.Repeater.OnPreRender(EventArgs e) +15
System.Web.UI.Control.PreRenderRecursiveInternal() +83
System.Web.UI.Control.PreRenderRecursiveInternal() +168
System.Web.UI.Control.PreRenderRecursiveInternal() +168
System.Web.UI.Control.PreRenderRecursiveInternal() +168
System.Web.UI.Control.PreRenderRecursiveInternal() +168
System.Web.UI.Control.PreRenderRecursiveInternal() +168
System.Web.UI.Control.PreRenderRecursiveInternal() +168
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterasyncPoint) +974

解决方法

我有同样的问题,意识到我正在使用错误的sqlFunction类型.请确保您引用了正确的命名空间:
using System.Data.Entity.sqlServer;

并不是:

using System.Data.Objects.sqlClient;

关于使用 python os.system 从 netstat 中提取端口并在变量中使用它python读取网络端口数据的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于# netstat -s、ASP.NET Core 3.1:System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.Int64”类型、Automapper 错误:System.InvalidOperationException:'缺少从 System.String 到 System.Char 的映射、c# – LINQ to Entities不识别方法’System.String StringConvert(System.Nullable`1 [System.Double])等相关知识的信息别忘了在本站进行查找喔。

本文标签: