对于使用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读取网络端口数据)
- # 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 中提取端口并在变量中使用它
我正在寻找一种从 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
[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”类型
Picture Error
我的控制器:
[HttpDelete("{roomId}")]
public async Task<IActionResult> Delete(string roomId)
{
var affectedResult = await _manageRoomService.Delete(roomId);
if (affectedResult == 0)
return BadRequest();
return Ok();
}
我的服务:我尝试调试,但它在代码块 foreach (var image in images)
中停止。
public async Task<int> Delete(string roomId)
{
var room = await _context.Rooms.FindAsync(roomId);
if (room == null)
throw new EWebHotelException($"Cannot find a room: {roomId}");
var images = _context.RoomImages.Where(i => i.RoomId == roomId);
foreach (var image in images)
{
await _storageService.DeleteFileAsync(image.ImagePath);
}
_context.Rooms.Remove(room);
return await _context.SaveChangesAsync();
}
我在 FileStorageService.cs 中的方法:
public async Task DeleteFileAsync(string fileName)
{
var filePath = Path.Combine(_userContentFolder,fileName);
if (File.Exists(filePath))
{
await Task.Run(() => File.Delete(filePath));
}
}
在 RoomImages 表中,列 Id
的类型为 int 32。
Automapper 错误:System.InvalidOperationException:'缺少从 System.String 到 System.Char 的映射
如何解决Automapper 错误:System.InvalidOperationException:''缺少从 System.String 到 System.Char 的映射
我需要使用 automapper 从 Company 模型中填充 CompanyVM 中的地址字段。一个公司可能有许多地址。最好我想要一个也是主要的活动地址。否则,我只想要一个活动地址。如果不行,给我一个地址。
这是公司模型:
public class Company
{
public int CompanyID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Industry { get; set; }
public string DBA { get; set; }
public string TaxID { get; set; }
public bool Active { get; set; } = true;
public virtual ICollection<Address> Addresses { get; set; } = new List<Address>();
这是地址模型:
public class Address
{
public int AddressID { get; set; }
public string Type { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string County { get; set; }
public string Country { get; set; }
public bool Primary { get; set; } = false;
public bool Active { get; set; } = true;
public int? CompanyCompanyID { get; set; }
我需要绘制其中的许多地图,但现在只是想让它为 Street1 工作。
以下是我尝试使用的自动映射器语句:
public class CompanyProfile : Profile
{
public CompanyProfile()
{
CreateMap<Company,CompanyVM>()
.ForMember(vm => vm.Street,opt => opt.MapFrom(model =>
model.Addresses.Where(x => x.CompanyCompanyID != null && x.Active && x.Primary).Select(x => x.Street1) ??
model.Addresses.Where(x => x.CompanyCompanyID != null && x.Active).Select(x => x.Street1) ??
model.Addresses.Where(x => x.CompanyCompanyID != null).Select(x => x.Street1)))
.ReverseMap();
}
}
这是 CompanyVM:
[Grid2(nameof(CompanyID),FavoritesEnabled = true,RecentRecordAction = "Details",FetchDataOnLoad = true
)]
public class CompanyVM : GridRecordVM
{
public virtual int CompanyID { get; set; }
[GridColumn2(TemplateType = GridTemplateType.DefaultDetailLink,IncludeInGeneralSearch = true)]
public virtual string Name { get; set; }
[GridColumn2]
public virtual string Type { get; set; }
[LockedFilter(FilterOperator.IsEqualTo,true)]
public virtual bool Active { get; set; }
[display(Name = "Industry")]
[MaxLength(20,ErrorMessage = "Industry cannot be longer that 20 characters.")]
public string Industry { get; set; }
[display(Name = "DBA")]
[MaxLength(50,ErrorMessage = "DBA name cannot be longer that 50 characters.")]
public string DBA { get; set; }
[display(Name = "Tax Id")]
[MaxLength(50,ErrorMessage = "TaxID name cannot be longer that 50 characters.")]
public string TaxID { get; set; }
[display(Name = "Street",Description = "Street")]
public string Street { get; set; }
//these items set to ignoremap until mapping sorted out
[display(Name = "City",Description = "City")]
[IgnoreMap]
public string City { get; set; }
[display(Name = "State",Description = "State")]
[IgnoreMap]
public string State { get; set; }
[display(Name = "ZipCode",Description = "ZipCode")]
[IgnoreMap]
public string ZipCode { get; set; }
[Phone]
[display(Name = "Phone Number",Description = "Phone Number")]
[IgnoreMap]
public string PhoneNumber { get; set; }
[EmailAddress]
[display(Name = "Email Address",Description = "Email Address")]
[IgnoreMap]
public string EmailAddress { get; set; }
}
抛出运行时错误:system.invalidOperationException: ''Missing map from System.String to System.Char。使用 CreateMap
解决方法
解决方案是将 CreateMap .ForMember 语句格式化如下:
CreateMap<Company,CompanyVM>()
.ForMember(x => x.Street,opt => opt.MapFrom(src =>
src.Addresses.Where(x => x.Active && x.Primary).FirstOrDefault() != null
? src.Addresses.Where(x => x.Active && x.Primary).FirstOrDefault().Street1
: src.Addresses.Where(x => x.Active).FirstOrDefault() != null
? src.Addresses.Where(x => x.Active).FirstOrDefault().Street1
: src.Addresses.FirstOrDefault() != null
? src.Addresses.FirstOrDefault().Street1
: string.Empty))
c# – LINQ to Entities不识别方法’System.String StringConvert(System.Nullable`1 [System.Double])
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
解决方法
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])等相关知识的信息别忘了在本站进行查找喔。
本文标签: